Walls and Gates
- 1 min read
- Graph
- LC-Medium
Solution
- Do a multi-source Breadth-first Search
- That's pretty much it lol
| Time | Space | Explanation |
|---|
O(mn) | O(mn) | |
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
nrows, ncols = len(rooms), len(rooms[0])
q = deque()
INF = 2147483647
for r in range(nrows):
for c in range(ncols):
if rooms[r][c] == 0:
q.append((r, c))
level = 1
while q:
for _ in range(len(q)):
r, c = q.popleft()
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = r + dr, c + dc
if nr >= 0 and nr < nrows and nc >= 0 and nc < ncols and rooms[nr][nc] == INF:
q.append((nr, nc))
rooms[nr][nc] = level
level += 1