题目
解法1:BFS
brutal force的从每一个空地出发,找与building的最短距离之和
class Solution:
def shortestDistance(self, grid: List[List[int]]) -> int:
def helper(i,j):
visited = set()
buildings = set()
q = collections.deque()
q.append((i,j,0))
visited.add((i,j))
total_step = 0
dirs = [[0,1],[0,-1],[-1,0],[1,0]]
while q:
i,j,step = q.popleft()
if grid[i][j] == 1 and (i,j) not in buildings:
total_step += step
buildings.add((i,j))
if len(buildings) == num_buildings:
break
if grid[i][j]!=1:
for d in dirs:
x = i+d[0]
y = j+d[1]
if 0<=x<m and 0<=y<n and (x,y) not in visited and grid[x][y]!=2:
q.append((x,y,step+1))
visited.add((x,y))
return total_step if len(buildings)==num_buildings else -1
m,n = len(grid),