Skip to main content

286. Walls and Gates

link

Find all gates, and start from all gates together.

class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""

m = len(rooms)
n = len(rooms[0])

dq = deque()

for i in range(m):
for j in range(n):
if rooms[i][j] == 0:
dq.append([(i, j), 0])


while dq:
lens = len(dq)

for _ in range(lens):
[(i, j), c] = dq.popleft()

for x , y in [(0,1),(0,-1),(1,0),(-1,0)]:
if not (0 <= i+x<m and 0<=j+y<n):
continue
if rooms[i+x][j+y] != 2 ** 31 - 1:
continue
rooms[i+x][j+y] = c + 1
dq.append([(i+x, j+y), c+1])



return