You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

The lock initially starts at '0000', a string representing the state of the 4 wheels.

You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

Examples

Example 1:

Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
Output: 6
Explanation:
A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
because the wheels of the lock become stuck after the display becomes the deadend "0102".

Example 2:

Input: deadends = ["8888"], target = "0009"
Output: 1
Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".

Example 3:

Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
Output: -1
Explanation: We cannot reach the target without getting stuck in a deadend.

Constraints

  • 1 <= deadends.length <= 500
  • deadends[i].length == 4
  • target.length == 4
  • target and deadends[i] consist of digits only.

Thinking Process

You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

The lock initially starts at '0000', a string representing the state of the 4 wheels.

  • BFS visits nodes in non-decreasing distance from the source.
  • Queue guarantees shortest path in unweighted graphs.
  • Process level by level when counting layers or distances.
Graph BFS layers S a b t BFS: expand by layers (queue)

Common Approaches

Typical techniques for this pattern:

Approach Time Space Notes
Queue BFS (this problem) O(n) O(n) Shortest path in unweighted graphs
Multi-source BFS O(n) O(n) Start from all sources simultaneously
0-1 BFS / deque O(n) O(n) Weights 0 or 1
Level-order BFS O(n) O(w) Process by depth/layer

Solution

Solution: BFS Shortest Path

class Solution {
public:
    int openLock(vector<string>& deadends, string target) {
        unordered_set<string> deads (deadends.begin(), deadends.end());
        unordered_set<string> visited;
        if(deads.contains("0000")) return -1;
        queue<string> q;
        q.push("0000");
        visited.insert("0000");
        int steps = 0;
        while(!q.empty()) {
            int size = q.size();
            while(size--) {
                string curr = q.front();
                q.pop();
                if(curr == target) return steps;
                for(int i = 0; i < 4; i++) {
                    for(int dir = -1; dir <=1; dir+=2) {
                        string next = curr;
                        next[i] = (curr[i] - '0' + dir + 10) % 10 + '0';
                        if(!deads.contains(next) && !visited.contains(next)) {
                            q.push(next);
                            visited.insert(next);
                        }
                    }
                }
            }
            steps++;
        }   
        return -1;
    }
};

Solution Explanation

Approach: Queue BFS (this problem)

Key idea: You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

How the code works:

  • BFS visits nodes in non-decreasing distance from the source.
  • Queue guarantees shortest path in unweighted graphs.
  • Process level by level when counting layers or distances.

Walkthrough — input deadends = ["0201","0101","0102","1212","2002"], target = "0202", expected output 6:

A sequence of valid moves would be “0000” -> “1000” -> “1100” -> “1200” -> “1201” -> “1202” -> “0202”. Note that a sequence like “0000” -> “0001” -> “0002” -> “0102” -> “0202” would be invalid, because the wheels of the lock become stuck after the display becomes the deadend “0102”.

Algorithm Explanation:

  1. Initialize: Create deadends set and visited set
  2. Check start: If “0000” is a deadend, return -1 immediately
  3. BFS setup: Start with “0000” in queue
  4. Level processing: Process all states at current level
  5. State transitions: For each position, try both directions (+1 and -1)
  6. Wrapping: Use modulo arithmetic for circular nature
  7. Validation: Check if next state is valid (not deadend, not visited)
  8. Target check: Return steps when target is reached

Example Walkthrough:

For deadends = ["0201","0101","0102","1212","2002"], target = "0202":

Level 0: ["0000"] → steps = 0
Level 1: ["1000", "9000", "0100", "0900", "0010", "0090", "0001", "0009"] → steps = 1
Level 2: ["2000", "1100", "1900", "0200", "0800", "0110", "0190", "0020", "0080", "0011", "0019", "0002", "0008"] → steps = 2
Level 3: Continue exploring...
...
Level 6: ["0202"] → Found target! Return 6

Path: "0000" → "1000" → "1100" → "1200" → "1201" → "1202" → "0202"

Key Implementation Details:

// Circular wrapping for digits
next[i] = (curr[i] - '0' + dir + 10) % 10 + '0';

// For dir = -1: (0 - 1 + 10) % 10 = 9 (0 → 9)
// For dir = +1: (9 + 1 + 10) % 10 = 0 (9 → 0)

Time Complexity: O(10^4) = O(1)

  • State space: At most 10,000 states (0000-9999)
  • BFS traversal: Each state visited at most once
  • Transitions: 8 transitions per state
  • Total: O(10,000 × 8) = O(80,000) = O(1) constant time

Space Complexity: O(10^4) = O(1)

  • Queue: O(10,000) - maximum states in queue
  • Visited set: O(10,000) - stores visited states
  • Deadends set: O(500) - stores deadend states
  • Total: O(10,000) = O(1) constant space

    Key Points

  1. BFS for shortest path: Guarantees minimum number of moves
  2. State space: 4-digit strings represent lock states
  3. Circular wrapping: Handle 0 ↔ 9 transitions correctly
  4. Deadend avoidance: Skip invalid states
  5. Visited tracking: Prevent infinite loops
  6. Level counting: Each BFS level represents one move

Common Mistakes

  • Skipping edge cases (empty input, single element, boundaries).
  • Off-by-one errors in loops and index ranges.
  • Forgetting to handle the case when no valid answer exists.

Tags

BFS, Shortest Path, Lock, State Space, Medium

Key Takeaways

  • BFS visits nodes in non-decreasing distance from the source.
  • Queue guarantees shortest path in unweighted graphs.
  • Process level by level when counting layers or distances.

References

Template Reference