Open the Lock

Shortest dial sequence to reach a 4-digit target avoiding deadends — BFS over 10000 states.

Medium
Time O(10000 * 8) Space O(10000)
LeetCode
5 min read
bfs graph

Problem#

You have a 4-wheel dial starting at “0000”. On each move you can rotate one wheel up or down by 1 (modulo 10). Given a list of forbidden codes (deadends), return the minimum number of moves to reach target, or -1 if impossible.

Examples#

  • deadends = ["0201","0101","0102","1212","2002"], target = "0202"6.
  • deadends = ["8888"], target = "0009"1.
  • deadends = ["0000"], target = "8888"-1.

Constraints#

  • 1 <= deadends.length <= 500. All strings are 4 digits.

Hints#

Hint 1
Each state has 8 neighbors — each wheel up or down.
Hint 2
BFS gives shortest path in unweighted graphs; treat deadends and visited as the same blocked set.

Approach#

BFS from “0000”. Generate the 8 neighbors by flipping each of the 4 digits up or down modulo 10. Skip deadends and already-seen states.

Solution#

Open the Lock
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
unordered_set<string> blocked(deadends.begin(), deadends.end());
if (blocked.count("0000")) return -1;
if (target == "0000") return 0;
queue<string> q;
q.push("0000");
blocked.insert("0000");
int steps = 0;
while (!q.empty()) {
++steps;
int sz = q.size();
for (int i = 0; i < sz; ++i) {
string cur = q.front(); q.pop();
for (int d = 0; d < 4; ++d) {
for (int delta : {1, -1}) {
string nxt = cur;
nxt[d] = static_cast<char>('0' + ((cur[d] - '0' + delta + 10) % 10));
if (blocked.count(nxt)) continue;
if (nxt == target) return steps;
blocked.insert(nxt);
q.push(nxt);
}
}
}
}
return -1;
}
};

Editorial#

The state space is exactly 10000, so BFS is trivially affordable. Merging the deadend set with the visited set means we never re-check membership separately. Bidirectional BFS from both "0000" and target would cut work roughly in half — useful when constraints scale up but unnecessary here.

Complexity#

  • Time: O(N) where N = 10000 states, each with 8 neighbors.
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.