286. Walls and Gates
At a Glance
- Topic: graphs
- Pattern: BFS (multi-source shortest path on grid)
- Difficulty: Medium
- Companies: Google, Meta, Amazon, Microsoft, Bloomberg
- Frequency: High
- LeetCode: 286
Problem (one-liner)
Grid: -1 wall, 0 gate, INF empty room. Fill each empty room with shortest Manhattan distance to any gate (in-place).
Recognition Cues
- Shortest steps on unweighted grid — BFS
- Many targets — multi-source BFS from all gates at once
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Per cell BFS —
O(n^2 m^2)— too slow. - Optimal — one multi-source BFS —
O(nm).
Optimal Solution
Go
func wallsAndGates(rooms [][]int) {
if len(rooms) == 0 {
return
}
rows := len(rooms)
cols := len(rooms[0])
const empty = 2147483647
queue := make([][2]int, 0)
for row := 0; row < rows; row++ {
for col := 0; col < cols; col++ {
if rooms[row][col] == 0 {
queue = append(queue, [2]int{row, col})
}
}
}
directions := [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
head := 0
for head < len(queue) {
cell := queue[head]
head++
for _, delta := range directions {
nextRow := cell[0] + delta[0]
nextCol := cell[1] + delta[1]
if nextRow < 0 || nextCol < 0 || nextRow >= rows || nextCol >= cols {
continue
}
if rooms[nextRow][nextCol] != empty {
continue
}
rooms[nextRow][nextCol] = rooms[cell[0]][cell[1]] + 1
queue = append(queue, [2]int{nextRow, nextCol})
}
}
}JavaScript
const EMPTY = 2147483647;
function wallsAndGates(rooms) {
if (rooms.length === 0) {
return;
}
const rows = rooms.length;
const cols = rooms[0].length;
const queue = [];
for (let row = 0; row < rows; row += 1) {
for (let col = 0; col < cols; col += 1) {
if (rooms[row][col] === 0) {
queue.push([row, col]);
}
}
}
const directions = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];
let head = 0;
while (head < queue.length) {
const cell = queue[head];
head += 1;
for (const [deltaRow, deltaCol] of directions) {
const nextRow = cell[0] + deltaRow;
const nextCol = cell[1] + deltaCol;
if (nextRow < 0 || nextCol < 0 || nextRow >= rows || nextCol >= cols) {
continue;
}
if (rooms[nextRow][nextCol] !== EMPTY) {
continue;
}
rooms[nextRow][nextCol] = rooms[cell[0]][cell[1]] + 1;
queue.push([nextRow, nextCol]);
}
}
}Walkthrough
Gates at distance 0; BFS relaxes INF neighbors to parentDist+1.
Invariant: First time a room dequeues, distance is minimal because BFS expands by increasing radius.
Edge Cases
- No gates — rooms stay
INF - All walls — nothing changes
Pitfalls
- DFS without memo may redo paths — BFS is simpler here
Similar Problems
- 994. Rotting Oranges — layered BFS on a grid
- 743. Network Delay Time — weighted shortest path (Dijkstra)
Variants
- Track predecessor for path reconstruction
Mind-Map Tags
#bfs #multi-source #grid #shortest-distance #in-place
Last updated on
Spotted something unclear or wrong on this page?