Solution: Open the Lock
Understand how to apply breadth-first search to solve the Open the Lock problem by navigating a 4-digit lock combination from an initial state to a target while avoiding blocked deadends. Learn to generate valid next states, avoid cycles, and determine the shortest path to unlock using BFS traversal.
We'll cover the following...
Statement
You are given a lock with '0' through '9'.
The wheels can rotate freely and wrap around cyclically; turning
'9'forward leads to'0', and turning'0’backward leads to'9'.Each move consists of rotating one wheel by one position (either forward or backward).
The lock starts from the initial state "0000".
You are also given a list of deadends, where each string represents a lock position that is blocked; if the lock reaches any of these positions, it becomes stuck and can no longer be turned.
Your goal is to reach a given target combination by performing the minimum number of moves, starting from "0000" and avoiding all dead ends.
If it is impossible to reach the target, return -1.
Constraints:
deadends.lengthdeadends[i].lengthtarget.lengthtargetwill not be in the listdeadends.targetanddeadends[i]consists of digits only.
Solution
The solution uses a Breadth-First Search (BFS) approach to find the minimum number of moves needed to reach the target lock combination from "0000", while avoiding dead ends. The key idea is to treat each -1.
Now, let’s walk through the steps of the solution:
Create two character maps,
nextSlotto map the current slot digit with its next slot digit), and prevSlotto map the current slot digit to its previous slot digit. Create a hash set, ...