Open the Lock
Open the Lock is LeetCode 752 (Medium). A combination lock has 4 wheels, each showing a digit from 0 to 9. The lock starts at "0000".
- One move turns one wheel by one slot, up or down.
- The wheels wrap around: turning
9up gives0, and turning0down gives9. deadendsis a list of codes that jam the lock. If the wheels ever show one of them, the lock stops turning, so a path may never pass through a deadend.
Given a target code, return the minimum number of moves to reach it from "0000", or -1 if it cannot be reached.
There are at most 500 deadends, and every code is exactly 4 digits, so the whole space is only 10⁴ codes.
- 1 <= deadends.length <= 500
- deadends[i].length == 4
- target.length == 4
- target will not be in the list deadends.
- target and deadends[i] consist of digits only.
Intuition
Treat each 4-digit code as a node in a graph. Each code has exactly 8 neighbours: pick one of 4 wheels and turn it up or down. Every move costs the same, one turn, so the question "fewest moves from 0000 to target" is a shortest path in an unweighted graph. That is what breadth-first search answers.
BFS visits codes in rings: first 0000, then every code 1 turn away, then every code 2 turns away, and so on. The first time it reaches target, the ring number is the minimum, because every shorter distance has already been fully explored.
Deadends are simply nodes the search may never enter.
"Minimum number of steps" between states, where every step costs the same and each state has a small fixed set of next states, is BFS on an implicit graph. You never build the graph; you generate neighbours on the fly. Open the Lock is the textbook case; Word Ladder (LeetCode 127), Minimum Genetic Mutation (433) and Sliding Puzzle (773) have the same shape.
Approach
Before reading on, write the function that lists the 8 neighbours of a code, including the wrap from 0 to 9. Then decide where the deadends go so the search never steps on one.
Seed the visited set with the deadends
seen = set(deadends), so the search treats every deadend as already explored and never steps onto one, with no separate check in the loop. If "0000" is in it, the lock is jammed before the first move: return -1. Otherwise add "0000" and put it in the queue.
Expand level by level
Keep a counter turns. Each pass of the outer loop processes exactly the codes that were in the queue when it began, which is one full ring, then does turns += 1. Every code popped during a pass is exactly turns moves from the start.
Generate the 8 neighbours
For each wheel i and each move in (+1, -1), set digit i to (digit + move) % 10. In Python % already maps -1 to 9; in C++ and Java add 10 before taking % 10. Any neighbour not in seen is added to seen and to the queue.
Stop at the target
When the popped code equals target, return turns: the first hit is the fewest moves. If the queue empties without finding it, every reachable code has been visited and the target is not one of them: return -1.
Code in Python, C++ and Java
seen before starting means BFS treats them as already visited and never steps on one; no separate check is needed.turns and start the next ring of 1.turns and start the next ring of 7.seen before starting means BFS treats them as already visited and never steps on one; no separate check is needed.turns and start the next ring of 8.seen before starting means BFS treats them as already visited and never steps on one; no separate check is needed.Common pitfalls
Forgetting the wrap-around in C++ or Java
nxt[i] = '0' + (code[i] - '0' + move) % 10;
nxt[i] = '0' + (code[i] - '0' + move + 10) % 10;
In C++ and Java -1 % 10 is -1, not 9, so turning 0 down produces the character before '0' instead of '9'. Adding 10 first keeps the value non-negative. Python's % already returns 9.
Marking a code seen when it is popped, not when it is queued
code = queue.popleft() seen.add(code)
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)Many codes share neighbours, so the same code gets queued many times before it is first popped. The answer stays correct, but the queue can grow several times larger and the run can time out.
Not checking whether 0000 is a deadend
seen = set(deadends) queue = deque(["0000"])
if "0000" in seen:
return -1If the starting code is jammed, no move is possible at all and the answer is -1, even when target is "0000". Without the check the search happily expands from a jammed lock.
Counting turns per pop instead of per level
code = queue.popleft() turns += 1
for _ in range(len(queue)):
...
turns += 1turns must count rings, not codes. Either process one full level per pass, or store the distance with each code in the queue as (code, d).
Edge cases
The first pop is "0000", which equals the target, so the answer is 0.
If all 8 neighbours of the target are deadends (LeetCode's third example, target "8888"), nothing can reach it. BFS learns that only after visiting every other reachable code, up to 10⁴ of them, which is still fast, and returns -1.
Complexity
Open the Lock FAQ
Why BFS and not DFS?
Every move costs the same, and BFS explores codes in order of distance, so the first time it reaches the target is guaranteed to be the fewest moves. DFS would find a path, often a very long one, and would have to search everything to be sure no shorter one exists.
How does bidirectional BFS speed up the solution?
Search from "0000" and from target at the same time, always expanding the smaller frontier, and stop when the two meet. Each side only needs to go about half the distance, and because the number of codes grows quickly with distance, that visits far fewer codes. It is the usual follow-up when an interviewer asks for something faster than plain BFS.
What does the Python solution use for the queue?
collections.deque, because popleft() is O(1). Popping from the front of a plain list is O(n) and makes the whole search much slower.