Loading problem...
You are faced with a 4-dial rotary combination lock, where each dial contains 10 numeric positions labeled from '0' through '9'. The dials operate in a circular manner, meaning rotating past '9' brings you back to '0', and rotating backward from '0' brings you to '9'. Each single movement consists of rotating exactly one dial by one position in either direction.
The lock begins at the initial state "0000", representing all four dials set to zero.
You are provided with an array of forbidden codes — configurations that must be avoided at all costs. If the lock ever displays any of these forbidden combinations, the security mechanism permanently locks down, preventing any further dial rotations.
Given a target code representing the combination that successfully unlocks the lock, determine the minimum number of individual dial movements required to transition from "0000" to the target configuration while avoiding all forbidden codes.
If it is impossible to reach the target code without triggering the security lockdown, return -1.
Key Observations:
forbiddenCodes = ["0201","0101","0102","1212","2002"]
targetCode = "0202"6One valid sequence of dial movements: "0000" → "1000" → "1100" → "1200" → "1201" → "1202" → "0202". This path requires 6 individual dial rotations. Note that the direct path through "0102" is blocked as it is a forbidden code.
forbiddenCodes = ["8888"]
targetCode = "0009"1From "0000", we can rotate the fourth dial backward (counterclockwise) once: "0000" → "0009". This takes only 1 movement since 0 and 9 are adjacent due to the circular dial design.
forbiddenCodes = ["8887","8889","8878","8898","8788","8988","7888","9888"]
targetCode = "8888"-1All possible final approaches to "8888" require passing through one of the forbidden codes. The configurations one step away from "8888" (differing by exactly one dial position in either direction) are all forbidden, making the target unreachable.
Constraints