SDE & MLE Prep

286. Walls and Gates

Problem

In the grid rooms, −1 is a wall, 0 is a gate and 2147483647 (INF) is an empty room. Fill every empty room, in place, with the number of steps to its nearest gate (moving up, down, left, right); rooms that can't reach a gate stay INF.

Example: [[INF,-1,0,INF],[INF,INF,INF,-1],[INF,-1,INF,-1],[0,-1,INF,INF]] → [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]

Multi-source BFS from every gate (0). The first time BFS reaches an empty room is its shortest distance.

Complexity: O(R·C).

class Solution:
    def wallsAndGates(self, rooms: List[List[int]]) -> None:
        INF = 2147483647
        R, C = len(rooms), len(rooms[0])
        q = deque((r, c) for r in range(R) for c in range(C) if rooms[r][c] == 0)
        while q:
            r, c = q.popleft()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < R and 0 <= nc < C and rooms[nr][nc] == INF:
                    rooms[nr][nc] = rooms[r][c] + 1
                    q.append((nr, nc))