Problem 517445 · medium · Phase 05 Advanced Algorithms & Graphs

Fewest Turns to Open a Dial Lock

BFS · state space · implicit graph

A padlock has three dials, each showing a digit 0 .. 9. A turn rotates one dial one step up or down, wrapping between 9 and 0. The lock starts at "000". Some combinations are jammed: if the lock ever shows a jammed combination it seizes and can no longer be turned. Given the list jammed and the opening combination target (three-character strings), return the minimum number of turns needed to show target, or -1 if it is impossible.

Examples

Input:  jammed = ["010"], target = "020"
Output: 4
Explanation: the direct route 000 -> 010 -> 020 is blocked; 000 -> 100 -> 110 -> 120 -> 020 takes 4 turns,
             and no 3-turn route exists.

Input:  jammed = ["000"], target = "123"
Output: -1
Explanation: the start position itself is jammed.

Input:  jammed = [], target = "000"
Output: 0

Constraints

  • 0 <= len(jammed) <= 1000, all strings have exactly three digits.
  • Target O(1000 * 6) time - the number of states times the moves per state.

Goals

  • Model lock states as nodes of an implicit graph
  • Generate neighbours by editing a string and skip forbidden states
Starting Python…