Parcel-delivery app~20 min2s · 256 MBtarget O(10^w × w²) time, O(10^w) spaceclassic twin: lc-752bfs
A parcel-delivery app uses code lockers. Each locker has a lock with wheels wheels, and every wheel shows a digit from 0 to 9. The lock starts at all zeros, and one turn moves a single wheel one step up or down. Digit 9 wraps round to 0, and 0 wraps to 9.
Your team lead says: "Some codes jam the lock. If the wheels ever show one, the lock stops for good. Tell me the fewest turns to reach the opening code."
Write fewest_turns(wheels, dead_ends, target).
wheels is the number of wheels. A code is a string of wheels digits.dead_ends lists the jammed codes. The lock can never show one of them, not even for a moment.target is the code that opens the locker.target without showing a jammed code. Return -1 when that is impossible, including when all zeros is itself jammed.If target is all zeros and it is not jammed, return 0.
Input: wheels = 1, dead_ends = ["1"], target = "3"
Output: 7Code "1" is jammed, so the lock cannot turn up from 0 and must go the long way down through 9. The search takes codes from a queue, oldest first.
| Code taken from the queue | Turns | New codes queued |
|---|---|---|
| "0" | 0 | "9" |
| "9" | 1 | "8" |
| "8" | 2 | "7" |
| "7" | 3 | "6" |
| "6" | 4 | "5" |
| "5" | 5 | "4" |
| "4" | 6 | "3" |
| "3" | 7 | target reached |
The turn count grows by one for every step of the ring, and "3" first leaves the queue after 7 turns.
Input: wheels = 2, dead_ends = ["01", "10", "90", "09"], target = "11"
Output: -1All four codes next to "00" are jammed, so the lock cannot make a first turn.
Input: wheels = 3, dead_ends = [], target = "000"
Output: 0The lock already shows the target.
1 ≤ wheels ≤ 40 ≤ len(dead_ends) ≤ 10,000, and every entry has wheels digitstarget has wheels digitsFour wheels allow at most 10,000 different codes, and each code has 8 neighbours. A search that meets each code once checks about 80,000 neighbours. Scanning a list of the codes seen so far for every neighbour would cost about 400 million comparisons.