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.
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.
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.
target is 4 digits.0 <= blocked.length <= 500Run 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).
I'm here to help with #431 Turning a Four-Wheel Code Lock. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.