Walls and Gates
Problem Statement
You get a grid of rooms. Each cell is one of three things:
- a wall (
-1): nothing can pass through it, - a gate (
0): a door out of the building, - an empty room (
INF, which is2147483647): it has not been filled yet.
Fill every empty room with the number of steps to its nearest gate. A step moves up, down, left or right to a neighbouring cell, and a path cannot go through a wall. If no gate can be reached from a room, it stays INF.
Change the grid in place. Walls and gates stay as they are.
rooms, an m × n grid. Each cell is -1 (wall), 0 (gate) or INF (empty room).
The same grid, changed in place: each empty room holds its distance to the nearest gate, or INF if no gate can be reached.
The top row is filled from the top-left gate: 1, 2, 3. The room at (0,4) is 2 steps from the bottom-right gate, going up the open right-hand column. It is 4 steps from the top-left gate, so the shorter distance is the one kept.
The wall in the middle forces paths to go round it. The room at (0,2) is 4 steps from the gate at (2,0): along the bottom row, then up past the wall.
- • m == rooms.length and n == rooms[i].length
- • Each cell is -1, 0 or 2147483647 (INF) at the start.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Run a separate BFS from each gate and keep the smallest distance for each room
Start with every gate in the queue; each empty room is filled the first time the wave reaches it
For each gate, run a BFS over the rooms that starts from that gate alone. Write each reached room's distance into a second grid, keeping the smallest value seen so far. When every gate has been searched, that second grid is the answer. Each gate costs a full BFS, so most rooms are measured again from every gate.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.