Open the Lock
A 4-wheel combination lock starts at '0000'. Each move rotates one wheel one notch up or down (9 wraps to 0 and 0 wraps to 9). A list of deadends are configurations the lock can never show. Return the minimum number of single-wheel turns to reach the target, or -1 if it is impossible.
Open official problem prompt ↗Find the least number of single-notch wheel turns transforming '0000' into a target combination without ever passing through a forbidden state.
Think of ripples spreading on a pond: BFS touches every combination exactly one turn away, then every combination two turns away, and so on. The instant the ripple reaches the target you know the exact distance.
- Input
- deadends = ["0201","0101","0102","1212","2002"], target = "0202"
- Output
- 6
- Why
- A valid shortest sequence is 0000 -> 1000 -> 1100 -> 1200 -> 1201 -> 1202 -> 0202, which takes 6 turns while avoiding every deadend.
1 <= deadends.length <= 500deadends[i].length == 4target.length == 4target is not in deadendstarget and deadends[i] consist of digits only