Open the Lock

You have a lock with 4 circular wheels, each showing the digits 0 to 9. The wheels wrap around: 9 turns to 0 and 0 turns to 9, and one move turns one wheel by one slot. The lock starts at "0000". You are given a list of deadends: if the lock ever shows one of them, the wheels jam. Given a target, return the minimum number of moves needed to open the lock, or -1 if it is impossible.

30:00

Open the Lock
medium
Free written solution
Topics
Companies

You have a lock with 4 circular wheels, each showing the digits 0 to 9. The wheels wrap around: 9 turns to 0 and 0 turns to 9, and one move turns one wheel by one slot. The lock starts at "0000". You are given a list of deadends: if the lock ever shows one of them, the wheels jam. Given a target, return the minimum number of moves needed to open the lock, or -1 if it is impossible.

Example 1:
Input: {"deadends":["0201","0101","0102","1212","2002"],"target":"0202"}
Output: 6
Constraints:
  • 1≤deadends.length≤5001 \leq \text{deadends.length} \leq 500

  • deadends[i].length==4\text{deadends}[i].\text{length} == 4

  • target.length==4\text{target.length} == 4

  • target will not be in the list deadends.

  • target and deadends[i] consist of digits only.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"deadends":["0201","0101","0102","1212","2002"],"target":"0202"}

Put the 5 dead ends in a set so each check is O(1). The lock starts at 0000 and must reach 0202.

1

0

9

wheel 1

1

0

9

wheel 2

1

0

9

wheel 3

1

0

9

wheel 4

showing 0000

target 0202

steps 0

BFS levels (combinations first reached after d turns)

not started

seen 0 of 10000 · queue 0

dead ends (5)

02010101010212122002
Variables
VariableValue
cur0000
steps0
queue0
seen0
DepthFunction Call
Stack empty
0/22