Open the Lock - Problem
Imagine you're a master thief standing before a sophisticated 4-digit combination lock. Each digit can be rotated from 0 to 9, and the wheels wrap around (so 9 becomes 0 and vice versa).
The lock starts at "0000" and you need to reach a specific target combination to unlock it. However, there's a catch - certain combinations are deadends that will trigger an alarm and lock you out forever!
Your mission: Find the minimum number of wheel turns needed to reach the target, or return -1 if it's impossible.
Rules:
- Each move rotates exactly one wheel by one position
- Wheels wrap around:
0 โ 9and9 โ 0 - Avoid all deadend combinations
- Find the shortest path from
"0000"to target
Input & Output
example_1.py โ Basic Case
$
Input:
deadends = ["0201","0101","0102","1212","2002"], target = "0202"
โบ
Output:
6
๐ก Note:
The shortest path is: 0000 โ 1000 โ 1100 โ 1200 โ 1201 โ 1202 โ 0202. We avoid deadends and find the minimum 6 moves.
example_2.py โ Impossible Case
$
Input:
deadends = ["8888"], target = "0009"
โบ
Output:
1
๐ก Note:
We can turn the last wheel from 0000 to 0009 in just 1 move. The deadend 8888 doesn't block our path.
example_3.py โ Blocked Start
$
Input:
deadends = ["0000"], target = "8888"
โบ
Output:
-1
๐ก Note:
The starting position 0000 is a deadend, so we cannot make any moves. Return -1 as it's impossible.
Constraints
- 1 โค deadends.length โค 500
- deadends[i].length == 4
- target.length == 4
- target will not be in the list deadends
- target and deadends[i] consist of digits only
Visualization
Tap to expand
Understanding the Visualization
1
Start at Ground Floor
Begin at room 0000 on floor 0
2
Explore Floor 1
Visit all rooms reachable in 1 move
3
Explore Floor 2
Visit all rooms reachable in 2 moves
4
Continue Until Target
The floor number when we find the target is our answer
Key Takeaway
๐ฏ Key Insight: BFS explores by distance levels, guaranteeing the shortest path to any reachable combination!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code