Open the Lock (LeetCode 752): Solution and Explanation
A 4-wheel combination lock starts at 0000. Each move turns one wheel up or down by one digit, with wrap-around. Some combinations jam the lock. Return the fewest moves to reach the target, or -1.
Intuition
Treat each of the 10,000 combinations as a node. Two combinations are connected when one wheel turn changes one into the other, so every node has exactly 8 neighbours.
All moves cost the same, so the fewest moves is the shortest path in an unweighted graph. Breadth-first search explores combinations in rings: first everything 1 turn away, then everything 2 turns away, and so on.
Dead ends are nodes you may never stand on, so they behave exactly like walls. Skip them the same way you skip combinations you have already visited.
Approach: Level-by-level BFS from 0000
- Put the dead ends in a set. If 0000 is a dead end, return -1 right away.
- Start a queue with 0000, mark it seen, and set
steps = 0. - Process the queue one level at a time. Pop each combination; if it equals the target, return
steps. - Otherwise build its 8 neighbours by turning each wheel up (+1) and down (+9 mod 10). Enqueue each one that is neither dead nor seen.
- After a full level, increase
steps. If the queue empties, return -1.
Step-by-step example
deadends = ["0201","0101","0102","1212","2002"], target = "0202"
- Level 0 is just 0000. Its 8 neighbours (1000, 9000, 0100, 0900, 0010, 0090, 0001, 0009) form level 1.
- Level 2 adds combinations like 0200 and 1100, but 0101 is a dead end, so it is never entered.
- Every 4-move route has to enter 0202 from 0102 or 0201, and both are dead ends, so no route of length 4 exists.
- The search goes around the blocked cells, for example 0000 -> 1000 -> 1100 -> 1200 -> 1201 -> 1202 -> 0202.
- 0202 is first popped at level 6, so the answer is 6.
Code: Python, Java, C++
1class Solution:
2 def openLock(self, deadends: List[str], target: str) -> int:
3 dead = set(deadends)
4 if "0000" in dead:
5 return -1
6 queue = deque(["0000"])
7 seen = {"0000"}
8 steps = 0
9 while queue:
10 for _ in range(len(queue)):
11 cur = queue.popleft()
12 if cur == target:
13 return steps
14 for i in range(4):
15 d = int(cur[i])
16 for move in (1, 9):
17 nxt = cur[:i] + str((d + move) % 10) + cur[i + 1:]
18 if nxt not in dead and nxt not in seen:
19 seen.add(nxt)
20 queue.append(nxt)
21 steps += 1
22 return -11class Solution {
2 public int openLock(String[] deadends, String target) {
3 Set<String> dead = new HashSet<>(Arrays.asList(deadends));
4 if (dead.contains("0000")) {
5 return -1;
6 }
7 Deque<String> queue = new ArrayDeque<>();
8 queue.offer("0000");
9 Set<String> seen = new HashSet<>();
10 seen.add("0000");
11 int steps = 0;
12 while (!queue.isEmpty()) {
13 for (int k = queue.size(); k > 0; k--) {
14 String cur = queue.poll();
15 if (cur.equals(target)) {
16 return steps;
17 }
18 char[] chars = cur.toCharArray();
19 for (int i = 0; i < 4; i++) {
20 char c = chars[i];
21 for (int move = 1; move <= 9; move += 8) {
22 chars[i] = (char) ('0' + (c - '0' + move) % 10);
23 String nxt = new String(chars);
24 if (!dead.contains(nxt) && seen.add(nxt)) {
25 queue.offer(nxt);
26 }
27 }
28 chars[i] = c;
29 }
30 }
31 steps++;
32 }
33 return -1;
34 }
35}1class Solution {
2public:
3 int openLock(vector<string>& deadends, string target) {
4 unordered_set<string> dead(deadends.begin(), deadends.end());
5 if (dead.count("0000")) {
6 return -1;
7 }
8 queue<string> q;
9 q.push("0000");
10 unordered_set<string> seen{"0000"};
11 int steps = 0;
12 while (!q.empty()) {
13 for (int k = q.size(); k > 0; k--) {
14 string cur = q.front();
15 q.pop();
16 if (cur == target) {
17 return steps;
18 }
19 for (int i = 0; i < 4; i++) {
20 for (int move : {1, 9}) {
21 string nxt = cur;
22 nxt[i] = '0' + (cur[i] - '0' + move) % 10;
23 if (!dead.count(nxt) && !seen.count(nxt)) {
24 seen.insert(nxt);
25 q.push(nxt);
26 }
27 }
28 }
29 }
30 steps++;
31 }
32 return -1;
33 }
34};Time and space complexity
O(10^4)
There are 10,000 combinations, each enqueued at most once, and each produces 8 neighbours of length 4.
O(10^4)
The seen set and the queue can hold every combination in the worst case.
Other approaches
Bidirectional BFS (time O(10^4), space O(10^4))
Grow one frontier from 0000 and one from the target, always expanding the smaller one, and stop when they touch. It explores far fewer combinations in practice, with the same worst case.
A* with circular wheel distance (time O(10^4 log 10^4), space O(10^4))
Use the sum over wheels of min(|a - b|, 10 - |a - b|) as a heuristic. It is admissible, so A* still returns the shortest answer, usually after visiting fewer nodes.
Common mistakes
- Forgetting that 0000 itself can be a dead end. In that case the answer is -1 even if the target is close.
- Turning a wheel down with
(d - 1) % 10, which is negative in Java, C++ and Go when d is 0. Add 9 instead, or add 10 before taking the remainder. - Marking a combination as seen when it is popped instead of when it is pushed. The same combination is then enqueued many times and the search slows down badly.
- Using depth-first search. DFS finds a route, but not necessarily the shortest one.
Frequently asked questions
Why does BFS give the minimum number of moves?
BFS visits every combination at distance d before any combination at distance d + 1. The first time it pops the target, no shorter route can exist.
Can the answer be larger than 20?
Without dead ends no wheel needs more than 5 turns, so 20 is the maximum. Dead ends can force detours, so a blocked lock can need more.
What if the target is 0000?
The first combination popped is the target, so the answer is 0, as long as 0000 is not a dead end.