Walls and Gates

Medium

Topics
GraphBFSMatrix

Fill each empty room with the distance to its nearest gate. -1 is a wall, 0 is a gate, and 2147483647 (INF) is an empty room. If a room cannot reach a gate, leave it as INF. Return the filled grid.

Example 1

03█011221█21█2█30█340123
gatesteps to the nearest gatewall
Each room shows the answer being asked for: its distance to the nearest gate, with ∞ for rooms no gate can reach.
2D grid — one row per line.
Input:  rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
Output: [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]

Constraints

  • 1 <= m, n <= 250
  • Each cell is -1, 0, or 2147483647.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Rather than BFS from each room, do one multi-source BFS starting from all gates at once. The first time BFS reaches a room, that is its shortest distance to any gate.

Approach

  1. Enqueue every gate (value 0).
  2. BFS outward; for each empty neighbour (INF), set its distance to current + 1 and enqueue it.
  3. Walls and already-filled rooms are skipped.

Dry Run

grid   INF  -1    0  INF          INF is an empty room, -1 a wall, 0 a gate
       INF  INF  INF   -1
       INF  -1   INF   -1
         0  -1   INF  INF
Every gate goes into the queue BEFORE the first wave, so distances spread from all
of them simultaneously.
  seed     gates at (0,2) and (3,0)
  wave 1   (1,2)=1  (0,3)=1  (2,0)=1
  wave 2   (2,2)=2  (1,1)=2  (1,0)=2
  wave 3   (3,2)=3  (0,0)=3
  wave 4   (3,3)=4
result    3  -1   0   1
          2   2   1  -1
          1  -1   2  -1
          0  -1   3   4
Multi-source is the whole idea. Each room is reached by the wave from its NEAREST
gate, because waves advance in lockstep and whichever arrives first claims the
cell -- no comparison between gates is ever made, and no room is visited twice.
Running a separate BFS from each room instead would be O((mn)^2); this is O(mn).
The INF test doubles as the visited marker. A cell is only enqueued while it still
holds 2147483647, so overwriting it with a distance is simultaneously the answer
and the "already claimed" flag. Walls at -1 never match and need no special case.
Note (0,0) gets 3, reached the long way round through (1,0), because the -1 at
(0,1) blocks the direct route. The BFS discovers that without any special
handling.

Complexity

  • Time — O(m*n): each room enqueued at most once.
  • Space — O(m*n): the BFS queue.

Common Pitfalls

  • Multi-source BFS from all gates avoids the O((mn)^2) cost of BFS-per-room.

Full Solution — all languages

class Solution:
    def wallsAndGates(self, grid):
        R,C=len(grid),len(grid[0])
        from collections import deque
        q=deque((r,c) for r in range(R) for c in range(C) if grid[r][c]==0)
        while q:
            r,c=q.popleft()
            for dr,dc in ((1,0),(-1,0),(0,1),(0,-1)):
                nr,nc=r+dr,c+dc
                if 0<=nr<R and 0<=nc<C and grid[nr][nc]==2147483647:
                    grid[nr][nc]=grid[r][c]+1; q.append((nr,nc))
        return grid
Asked at DoorDash
SensAI
Beta
Tap the mic to stop voice mode