class Solution:
"""
@param rooms: m x n 2D grid
@return: nothing
"""
def wallsAndGates(self, rooms):
# write your code here
if not rooms or len(rooms) == 0 or len(rooms[0]) == 0:
return
m, n = len(rooms[0]), len(rooms)
import queue
qx = queue.Queue()
qy = queue.Queue()
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
for i in range(n):
for j in range(m):
if rooms[i][j] == 0:
qx.put(i)
qy.put(j)
while not qx.empty():
cx = qx.get()
cy = qy.get()
for i in range(4):
nx = cx +dx[i]
ny = cy +dy[i]
if nx >= 0 and nx < n and ny >= 0 and ny < m and rooms[nx][ny] == 2**31 - 1:
qx.put(nx)
qy.put(ny)
rooms[nx][ny] = rooms[cx][cy] + 1
Time O(nm). Space O(nm).