Lintcode 573 · Build Post Office

该博客介绍了一种算法问题,即在二维网格中找到一个位置建立邮局,使得邮局到所有房屋的总距离最小。算法通过广度优先搜索(BFS)遍历每个房屋并记录可达的空格子及其距离,最终找出连接所有房屋且距离最短的空格子作为邮局位置。若无法找到符合条件的位置,则返回-1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Lintcode 573 · Build Post Office

Description

Given a 2D grid, each cell is either a wall 2, an house 1 or empty 0 (the number zero, one, two), find a place to build a post office so that the sum of the distance from the post office to all the houses is smallest.

Returns the sum of the minimum distances from all houses to the post office.Return -1 if it is not possible.
You cannot pass through wall and house, but can pass through empty.
You only build post office on an empty.

Note

  • start from 1, and find all the reachable 0s. – BFS
  • for each 0, record the number of 1s the 0 is linked with, and the distance to all linked 1s
  • find the 0 which is connected with all 1s and has shortest distance.

Code

    def shortest_distance(self, grid: List[List[int]]) -> int:
        if not grid:
            return -1
        rows = len(grid)
        cols = len(grid[0])

        total_buildings = 0
        '''
        record the number of total buildings
        and the number of buildings each 0 can reach
        and their distance
        '''
        num_reach = [[0] * cols for _ in range(rows)]
        dist = [[0] * cols for _ in range(rows)]
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

        for i in range(rows):
            for j in range(cols):
                if grid[i][j] == 1:
                '''
                for each house, bfs all the reachable 0s
                to get the dist and num_reach of each 0
                '''
                    total_buildings += 1
                    self.bfs(grid, i, j, dist, num_reach, directions)

        min_dist = float('inf')
        for i in range(rows):
            for j in range(cols):
                if num_reach[i][j] == total_buildings:
                    if dist[i][j] < min_dist:
                        min_dist = dist[i][j]

        if min_dist == float('inf'):
            return -1
        return min_dist
        
    def bfs(self, grid, x, y, dist, num_reach, directions):
        queue = collections.deque([(x, y)])
        visited = set([(x, y)])
        d = 0
        '''
        bfs by level for distance calculation
        bfs starts from 1 and go to find all the 0s that can be reached by this 1
        '''
        while queue:
        '''
        d is the distance from the start 1 to current level. 
        we are going to find the next 0s
        the distance to next 0 = current d + 1
        '''
            d += 1
            current_size = len(queue)
            for _ in range(current_size):
                current_pos = queue.popleft()
                for (n_x, n_y) in self.get_neighbors(current_pos, grid, directions):
                    if (n_x, n_y) in visited:
                        continue
                        '''
                        n_x, n_y is the position of next 0 that can be reached by current_pos
                        '''
                    dist[n_x][n_y] += d
                    num_reach[n_x][n_y] += 1
                    queue.append((n_x, n_y))
                    visited.add((n_x, n_y))
    
    def get_neighbors(self, pos, grid, directions):
        neighbors = []
        for (x, y) in directions:
            new_x, new_y = pos[0] + x, pos[1] + y
            if 0 <= new_x < len(grid) and 0 <= new_y < len(grid[0]) and grid[new_x][new_y] == 0:
                neighbors.append((new_x, new_y))
        return neighbors

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值