Walls and Gates
Medium
Topics
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
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
- Enqueue every gate (value 0).
- BFS outward; for each empty neighbour (INF), set its distance to current + 1 and enqueue it.
- 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 gridimport java.util.*;
class Solution {
public int[][] wallsAndGates(int[][] grid) {
int R=grid.length,C=grid[0].length;
Deque<int[]> q=new ArrayDeque<>();
for(int r=0;r<R;r++)for(int c=0;c<C;c++)if(grid[r][c]==0)q.add(new int[]{r,c});
int[] dr={1,-1,0,0},dc={0,0,1,-1};
while(!q.isEmpty()) {
int[] cur=q.poll();
for(int d=0;d<4;d++) {
int nr=cur[0]+dr[d],nc=cur[1]+dc[d];
if(nr>=0&&nr<R&&nc>=0&&nc<C&&grid[nr][nc]==2147483647) {
grid[nr][nc]=grid[cur[0]][cur[1]]+1;
q.add(new int[]{nr,nc});
}
}
}
return grid;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> wallsAndGates(vector<vector<int>>& grid) {
int R=grid.size(),C=grid[0].size();
queue<pair<int,int>> q;
for(int r=0;r<R;r++)for(int c=0;c<C;c++)if(grid[r][c]==0)q.push({r,c});
int dr[]={1,-1,0,0},dc[]={0,0,1,-1};
while(!q.empty()) {
auto cur=q.front();
q.pop();
for(int d=0;d<4;d++) {
int nr=cur.first+dr[d],nc=cur.second+dc[d];
if(nr>=0&&nr<R&&nc>=0&&nc<C&&grid[nr][nc]==2147483647) {
grid[nr][nc]=grid[cur.first][cur.second]+1;
q.push({nr,nc});
}
}
}
return grid;
}
};/**
* @param {number[][]} grid
* @return {number[][]}
*/ var wallsAndGates = function(grid) {
const R=grid.length,C=grid[0].length,q=[];
for(let r=0;r<R;r++)for(let c=0;c<C;c++)if(grid[r][c]===0)q.push([r,c]);
let idx=0;
while(idx<q.length) {
const cur=q[idx++],r=cur[0],c=cur[1];
for(const d of [[1,0],[-1,0],[0,1],[0,-1]]) {
const nr=r+d[0],nc=c+d[1];
if(nr>=0&&nr<R&&nc>=0&&nc<C&&grid[nr][nc]===2147483647) {
grid[nr][nc]=grid[r][c]+1;
q.push([nr,nc]);
}
}
}
return grid;
};
Asked at
DoorDash