Problem Description
You are given a lock with 4 wheels, each with digits from '0' to '9'. Starting from "0000", you need to reach a given target combination by turning one wheel one slot at a time. However, if you hit any combination from a list of deadends, the lock gets permanently stuck. The task is to determine the minimum number of moves required to reach the target combination, or return -1 if it's not possible.
Key Insights
- This problem can be modeled as a graph where each node represents a 4-digit combination.
- Each valid move from one node generates up to 8 neighboring combinations (one for each wheel moving one step forward or backward).
- Breadth-First Search (BFS) is used to explore the graph level by level, which naturally finds the shortest path.
- Deadends must be avoided during the traversal.
- The initial state "0000" must be checked against the deadends.
Space and Time Complexity
Time Complexity: O(10^N) where N is the number of wheels (N = 4 gives 10^4 combinations in worst-case scenario). Space Complexity: O(10^N) due to storing visited states and the queue in BFS.
Solution
We use a Breadth-First Search (BFS) to systematically explore all potential combinations starting from "0000". Each combination represents a state or node in our search space. From each state, we generate all valid next states by incrementing or decrementing each digit (with wraparound behavior). We keep track of combinations that are either deadends or already visited to avoid cycles and unnecessary processing.
Key steps:
- Start at "0000" if it is not a deadend.
- Use a queue to process one level of combinations at a time, representing the number of moves.
- For each combination, generate all possible next moves (neighbors). Skip any that are deadends or that have been visited.
- If the target combination is reached, return the level (move count).
- If the queue empties without finding the target, return -1.