← Back to Visualizer Gallery
Traversal · State-Space BFS LeetCode 752

Open the Lock / implicit graph & deadends

The lock's 4 wheels represent an unmaterialized state graph with $10^4 = 10,000$ vertices. Pre-seed deadends into the visited set and launch a level-by-level BFS across 8 rotational neighbors per node.

Execution Stage

idle
INVARIANT State-Space BFS Invariant: Vertices are generated dynamically on push. Deadends are pre-seeded into the visited set before BFS starts, making deadend avoidance $O(1)$ and eliminating special case checks.
Pre-seeded Deadends 0 deadends
Active BFS Queue Frontier 0 nodes
Press Run to trace BFS state expansion.
0 / 0
Speed

Java · Reference Algorithm

INTERVIEW SCRIPT

How to Present Open the Lock to an Interviewer

1. The Implicit State Graph

"The graph is not given as an adjacency list. The vertices are strings from '0000' to '9999' ($10^4 = 10,000$ possible nodes). Each state has exactly 8 neighbors formed by turning each of the 4 wheels $\pm 1$ modulo 10."

2. Pre-seeding Deadends

"Rather than repeatedly querying a deadends set inside the loop, we initialize our visited set with all deadends upfront. If '0000' is a deadend, it is caught instantly at step 0."

3. Level-by-Level Distance

"Because each wheel turn costs 1 unit, BFS guarantees finding the minimum number of turns to reach the target on the first encounter."

4. Bidirectional BFS Optimization

"For interview depth, mention bidirectional BFS: expanding simultaneously from '0000' and 'target' reduces search complexity from $b^d$ to $2 b^{d/2}$ where $b=8$."

Open the Lock (LC 752) — Implicit state graph BFS · Time $O(d \cdot 10^d)$, Space $O(10^d)$ with $d=4$.