-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0286-walls-and-gates.py
39 lines (35 loc) · 1013 Bytes
/
0286-walls-and-gates.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution:
"""
@param rooms: m x n 2D grid
@return: nothing
"""
def walls_and_gates(self, rooms: List[List[int]]):
ROWS, COLS = len(rooms), len(rooms[0])
visit = set()
q = deque()
def addRooms(r, c):
if (
min(r, c) < 0
or r == ROWS
or c == COLS
or (r, c) in visit
or rooms[r][c] == -1
):
return
visit.add((r, c))
q.append([r, c])
for r in range(ROWS):
for c in range(COLS):
if rooms[r][c] == 0:
q.append([r, c])
visit.add((r, c))
dist = 0
while q:
for i in range(len(q)):
r, c = q.popleft()
rooms[r][c] = dist
addRooms(r + 1, c)
addRooms(r - 1, c)
addRooms(r, c + 1)
addRooms(r, c - 1)
dist += 1