You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 =2147483647to representINFas you may assume that the distance to a gate is less than2147483647
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled withINF
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
if not rooms:
return
n,m = len(rooms),len(rooms[0])
d = [-1,0,1,0,-1]
q = [(x,y) for x in range(n) for y in range(m) if rooms[x][y] == 0]
while q:
x,y = q.pop()
for nx, ny in [(x+d[i],y+d[i+1]) for i in range(4)]:
if 0 <= nx < n and 0<= ny < m and rooms[nx][ny] != -1 and rooms[nx][ny] > rooms[x][y] + 1:
rooms[nx][ny] = rooms[x][y] + 1
q.append((nx,ny))