317. Shortest Distance from All Buildings
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.
def shortestDistance(self, grid: List[List[int]]) -> int:
buildings = []
m = len(grid)
n = len(grid[0])
inf = float('inf')
dist = [[0] * n for _ in range(m)]
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def inbound(i, j):
return 0 <= i < m and 0 <= j < n
def neighbors(i, j):
for dx, dy in dirs:
newx, newy = i + dx, j + dy
if inbound(newx, newy) and grid[newx][newy] == identifier:
yield newx, newy
def bfs(i, j):
visited = set()
q = collections.deque([(i, j, 0)])
visited.add((i, j))
while q:
a, b, d = q.popleft()
dist[a][b] += d
for x, y in neighbors(a, b):
if grid[x][y] == identifier:
grid[x][y] -= 1
q.append((x, y, d + 1))
identifier = 0 # This is a super trick
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
bfs(i, j)
identifier -= 1
res = inf
for i in range(m):
for j in range(n):
if grid[i][j] == identifier:
res = min(res, dist[i][j])
return -1 if res == float('inf') else res