#286
Walls and Gates
medium· Graphsruns: 0You are given an m x n grid rooms initialized with one of three values: -1 for a wall, 0 for a gate, and 2147483647 (INT_MAX) for an empty room. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, leave the room as INT_MAX. Modify the grid in place.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 781
from collections import deque
class Solution:
def wallsAndGates(self, rooms: list[list[int]]) -> None:
if not rooms:
return
rows, cols = len(rooms), len(rooms[0])
queue = deque()
for r in range(rows):
for c in range(cols):
if rooms[r][c] == 0:
queue.append((r, c))
while queue:
r, c = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if (
0 <= nr < rows
and 0 <= nc < cols
and rooms[nr][nc] == 2147483647
):
rooms[nr][nc] = rooms[r][c] + 1
queue.append((nr, nc))
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.