← Visualizers
Graphs · Grid BFS, unweighted shortest path LeetCode 1091

Shortest Path in Binary Matrix / visualized

A BFS level is a distance. Eight directions, a size snapshot taken before each level, and the one line the whole pattern rests on: mark on push, in the same statement that enqueues. Flip the toggle to run the mark-on-pop version and watch the queue.

Execution

idle
INVARIANT Mark ON PUSH. Level snapshot sz = q.size() ensures all distance-d cells are processed before any distance-(d+1).
Processing Wave (Level d)
Enqueued Wave (Level d+1)
Press Run to begin.
0 / 0
Speed

Java · running line

popped now in queue settled distance shortest path blocked
INTERVIEW SCRIPT

How to Explain Shortest Path in Binary Matrix to an Interviewer

1. Unweighted Shortest Path = BFS

"Since all 8 directional moves have equal unit weight of 1, BFS is guaranteed to discover the target node in the minimum number of steps."

2. The Mark-on-Push Invariant

"We MUST mark seen[nr][nc] = true at the exact moment of enqueuing. If you mark on pop, multiple active wavefront cells enqueue the same neighbor, blowing up the queue exponentially and corrupting shortest path distances!"

3. Level Snapshot with sz = q.size()

"Taking a snapshot of the queue size guarantees that all nodes at distance $d$ are exhausted before any node at distance $d+1$ is polled."

4. Complexity Mastery

"Each grid cell is pushed to the queue at most once. Time is $O(n^2)$ and auxiliary space is $O(n^2)$ queue memory."

O(n²) time, O(n²) space  ·  marking on pop is not merely slower. The same cell is enqueued once per neighbour that reaches it, each push overwrites its recorded distance with a longer one, and the answer comes back too large — failure mode 1.1, a distance greater than the true minimum.