You are given an m x n grid grid of values 0, 1, or 2, where:
each 0 marks an empty land that you can pass by freely,
each 1 marks a building that you cannot pass through, and
each 2 marks an obstacle that you cannot pass through.
You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right.Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1.The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]Output: 7Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2).The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal.So return 7.
from collections import dequeclass Solution: # Time: O(b * m * n) — one BFS per building (b = building count) # Space: O(m * n) def shortest_distance(self, grid: list[list[int]]) -> int: m, n = len(grid), len(grid[0]) total = [[0] * n for _ in range(m)] reach = [[0] * n for _ in range(m)] building_count = sum(row.count(1) for row in grid) for i in range(m): for j in range(n): if grid[i][j] != 1: continue distance = [[-1] * n for _ in range(m)] distance[i][j] = 0 queue: deque[tuple[int, int]] = deque([(i, j)]) while queue: r, c = queue.popleft() for x, y in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)): if 0 <= x < m and 0 <= y < n and grid[x][y] == 0 and distance[x][y] < 0: distance[x][y] = distance[r][c] + 1 queue.append((x, y)) for r in range(m): for c in range(n): if distance[r][c] >= 0: total[r][c] += distance[r][c] reach[r][c] += 1 best = -1 for i in range(m): for j in range(n): if ( grid[i][j] == 0 and reach[i][j] == building_count and (best < 0 or total[i][j] < best) ): best = total[i][j] return best