Skip to the code
cf.
+25 XP

#431 Turning a Four-Wheel Code Lock

medium

A settings page shows a 4-digit lock with four wheels. It starts at "0000". One move turns a single wheel one notch up or down, and the wheels wrap around: turning 9 up gives 0, and turning 0 down gives 9.

Some codes in blocked freeze the lock, so the lock must never show any of them, including at the start. Write fewestTurns(target, blocked) that returns the fewest moves to reach target, or -1 if it can't be done.

Example 1

Input: target = "0202", blocked = ["0201","0101","0102","1212","2002"]
Output: 6

Every 4-move route passes a blocked code, so the lock detours: 0000 → 1000 → 1100 → 1200 → 1201 → 1202 → 0202.

Example 2

Input: target = "8888", blocked = ["8887","8889","8878","8898","8788","8988","7888","9888"]
Output: -1

Every code one move away from 8888 is blocked, so it can never be reached.

Constraints

  • target is 4 digits.
  • 0 <= blocked.length <= 500
  • Each blocked code is 4 digits.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).