← Visualizers
Graphs · Multi-source BFS LeetCode 286

Walls and Gates / visualized

Searching from every empty room to find its nearest gate takes $O((m \cdot n)^2)$. Instead, push all gates (0) into the queue at once and radiate outward. Overwriting an empty room's INF value immediately seals it as visited, producing the global distance map in a clean $O(m \cdot n)$ single sweep.

Grid · Radiation Wave

idle
INVARIANT Multi-Source Gate Invariant: Enqueue ALL gates (0) simultaneously at t=0. Radiate BFS outward: if rooms[nr][nc] == INF, update rooms[nr][nc] = rooms[r][c] + 1 and enqueue. Overwriting INF acts as the visited guard, guaranteeing O(m·n) time and 0 redundant visits!
Press Run to begin.
0 / 0
Speed

Java · running line

gate (0) wall (-1) filled distance popping now
INTERVIEW SCRIPT

How to Explain Walls and Gates to an Interviewer

1. Forward vs Reverse Direction

"Searching forward from empty rooms to find gates costs $O((m \cdot n)^2)$. By reversing perspective and flooding from all gates outward simultaneously, every cell is visited at most once in $O(m \cdot n)$."

2. Multi-Source Seeding

"Scan the entire grid initially. Whenever rooms[r][c] == 0, add [r, c] to the queue. All gates begin at distance 0 together before any pop occurs."

3. In-Place Visited Invariant

"We do not need a separate visited[][] matrix. An empty room holds Integer.MAX_VALUE (INF). If rooms[nr][nc] == INF, we set rooms[nr][nc] = rooms[r][c] + 1 on push, immediately guarding it from duplicate visits."

4. Unreachable Rooms

"Rooms surrounded by walls are never reached by the BFS wave. They naturally retain their initial INF value as mandated by the problem specification."

O(m·n) time, O(m·n) space  ·  multi-source BFS directly overwrites INF in-place.