jinhuang1102

286. Walls and Gates

Nov 25th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. from collections import deque
  2.  
  3. class Solution(object):
  4.     def neighbors(self, rooms, x, y):
  5.         dx = [0,0,-1,1]
  6.         dy = [-1,1,0,0]
  7.            
  8.         q = deque()
  9.         q.append((x,y))
  10.         step = 1
  11.        
  12.         while q:
  13.             num = len(q)
  14.             for i in range(0, num):
  15.                 xx, yy = q.popleft()
  16.                 for i in range(4):
  17.                     rx, ry = xx + dx[i], yy + dy[i]
  18.                     if rx < 0 or ry < 0 or rx > len(rooms)-1 or ry > len(rooms[0])-1:
  19.                         continue
  20.                     if rooms[rx][ry] > 0 and rooms[rx][ry] > step:
  21.                         rooms[rx][ry] = step
  22.                         q.append((rx, ry))
  23.  
  24.             step += 1
  25.                            
  26.                
  27.     def wallsAndGates(self, rooms):
  28.         """
  29.        :type rooms: List[List[int]]
  30.        :rtype: void Do not return anything, modify rooms in-place instead.
  31.        """
  32.         if not rooms or not rooms[0]:
  33.             return
  34.                
  35.         for i in range(0, len(rooms)):
  36.             for j in range(0, len(rooms[0])):
  37.                 if rooms[i][j] == 0:
  38.                     self.neighbors(rooms, i, j)
Add Comment
Please, Sign In to add comment