{"id":"open-the-lock","title":"Open the Lock","difficulty":"medium","patterns":["graph-bfs"],"primaryConcept":"graph-shortest-path-unweighted","concepts":["graph-shortest-path-unweighted"],"problemForm":"core","companies":["Google","Amazon","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"string-list","primaryParam":"deadends","sizeMetric":"total-length","sizes":[8,16,32],"secondaryParams":{"target":{"strategy":"fixed","value":"0202"}}},"description":"You have a lock with four wheels. Each wheel shows one digit from 0 to 9 and can rotate forward or backward by one digit, wrapping around between 0 and 9.\n\nGiven a list of deadend combinations and a target combination, return the minimum number of turns needed to reach the target from `\"0000\"`. Return `-1` if it is impossible.","examples":[{"input":"deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"","output":"6","explanation":"The shortest path avoids the deadends and reaches 0202 in six turns."},{"input":"deadends = [\"8888\"], target = \"0009\"","output":"1","explanation":"Rotate the last wheel backward once from 0000 to 0009."}],"constraints":[{"id":"1-len-deadends-500","text":"1 <= len(deadends) <= 500","check":{"kind":"sizeRange","target":"deadends","measure":"arrayLength","min":1,"max":500}},{"id":"deadends-i-length-4","text":"len(deadends[i]) == 4","check":{"kind":"valueRange","target":"deadends","selector":"arrayItemLengths","min":4,"max":4}},{"id":"target-length-4","text":"len(target) == 4","check":{"kind":"sizeRange","target":"target","measure":"stringLength","min":4,"max":4}},{"id":"deadends-i-and-target-contain-only-digits","text":"deadends[i] and target contain only digits"}],"starterCode":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        # Your code here\n        pass","functionName":"openLock","testCases":[{"id":"1","input":{"deadends":["0201","0101","0102","1212","2002"],"target":"0202"},"expected":6,"description":"Canonical shortest path around deadends."},{"id":"2","input":{"deadends":["8888"],"target":"0009"},"expected":1,"description":"One wraparound move."},{"id":"3","input":{"deadends":["8887","8889","8878","8898","8788","8988","7888","9888"],"target":"8888"},"expected":-1,"description":"The target is surrounded by deadends."},{"id":"4","input":{"deadends":["0000"],"target":"8888"},"expected":-1,"description":"The start state is blocked."},{"id":"h1","input":{"deadends":["9999"],"target":"0000"},"expected":0,"description":"The start state already matches the target."},{"id":"h2","input":{"deadends":["9999"],"target":"1000"},"expected":1,"description":"One forward turn reaches the target."},{"id":"h3","input":{"deadends":["0001"],"target":"0002"},"expected":4,"description":"A blocked direct step can still be bypassed with a short detour."},{"id":"h4","input":{"deadends":["9999"],"target":"0202"},"expected":4,"description":"Two wheels each need two turns."},{"id":"h5","input":{"deadends":["1111"],"target":"9999"},"expected":4,"description":"Four backward turns solve the all-nines target."},{"id":"h6","input":{"deadends":["8888"],"target":"8888"},"expected":-1,"description":"A deadend target is impossible to reach."},{"id":"topup-one-move","input":{"deadends":["1111"],"target":"0009"},"expected":1,"description":"Wrapping one wheel backward reaches the target in one move."},{"id":"topup-blocked-origin","input":{"deadends":["0001","0010","0100","1000","0009","0090","0900","9000"],"target":"8888"},"expected":-1,"description":"If the origin is dead, the lock cannot be opened."}],"hints":[{"level":1,"content":"Every four-digit combination is a graph node."},{"level":2,"content":"Each state has eight neighbors: one step forward or backward on each of four wheels."},{"level":3,"content":"Use BFS from 0000 so the first time you reach target is the minimum number of turns."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"dfs-search","name":"Depth-first search","summary":"Dive down one route to its end, then back out and try the next route.","decisionReason":"Going deep commits to a single route and can land on target the long way first, so it cannot certify the route it found is shortest until it has exhausted the other routes. That is the same route-chasing blow-up the slow baseline showed.","complexity":{"time":"O(routes)","space":"O(10000)"},"tradeoffs":["First arrival on target is not guaranteed shortest, so it must keep searching to confirm the minimum."],"isOptimal":false},{"id":"bfs-shortest-path","name":"BFS shortest path","summary":"Spread outward in FIFO distance rings from 0000 and stop the instant target is dequeued.","decisionReason":"FIFO order processes every state at distance k before any at distance k+1, so the first time target comes off the queue is already the fewest moves and the search can stop. Each state is visited once.","complexity":{"time":"O(10000)","space":"O(10000)"},"tradeoffs":["First arrival on target is final, so it visits each of the 10000 states at most once."],"isOptimal":true}]},"codingCheckpoints":[{"id":"guard-start-dead","title":"Reject a blocked start","description":"If \"0000\" is a deadend, return -1 before starting BFS.","commonMistakes":["Starting BFS from a forbidden state","Returning 0 when the start is blocked"],"hint":"Build deadend membership, then check whether \"0000\" is blocked before seeding the queue.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"short_circuits_trivial_case","scope":"start-dead","readMode":"bfs-queue-value-query-v1","expected":{"seedLiteral":"0000","unreachableSentinel":-1}}]},"semanticSpec":{"intent":"Stop immediately when the starting lock state is forbidden.","doneWhen":"The code checks deadend membership for \"0000\" and returns -1 before traversal.","shouldFailWhen":"The code starts BFS from \"0000\" even when it is a deadend or returns the wrong value.","roles":["deadend membership","start state","blocked return"],"mustProve":["The blocked start state returns -1 before BFS begins."],"mustNotAccept":["Checking some other state before BFS.","Returning a non-negative distance for a blocked start."],"proofSnippets":[{"id":"py-open-lock-guard-start-dead","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1"}]}},{"id":"init-queue","title":"Initialize BFS state","description":"Seed the BFS queue with \"0000\" at distance 0.","commonMistakes":["Starting BFS even when 0000 is dead","Seeding the queue without the starting distance"],"hint":"The queue starts with (\"0000\", 0).","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"initializes_frontier_and_aux_state","scope":"init-distance-queue","readMode":"bfs-queue-value-query-v1","expected":{"seedLiteral":"0000"}}]},"semanticSpec":{"intent":"Seed the BFS frontier from the starting lock state.","doneWhen":"The queue contains (\"0000\", 0) before traversal.","shouldFailWhen":"The code has no queue frontier or does not seed the starting distance.","roles":["queue","start state","distance"],"mustProve":["The solution initializes BFS frontier and auxiliary state."],"mustNotAccept":["A traversal with no visited state."],"proofSnippets":[{"id":"py-open-lock-init-queue","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]"}]}},{"id":"bfs-loop","title":"Drive the queue loop","description":"Process states while the BFS frontier still has queued entries.","commonMistakes":["Using a stack-style traversal","Forgetting to advance the queue head"],"hint":"Continue while the head position is before the end of the queue, then increment head after reading the current state.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"loops_while_frontier_non_empty","scope":"bfs-loop","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Consume the BFS frontier in FIFO order.","doneWhen":"The loop reads queued states and advances the frontier pointer.","shouldFailWhen":"The frontier is never consumed or the loop is not queue-driven.","roles":["queue","head index"],"mustProve":["The solution loops while the frontier is non-empty."],"mustNotAccept":["A loop unrelated to queued lock states."],"proofSnippets":[{"id":"py-open-lock-bfs-loop","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1"}]}},{"id":"return-target","title":"Return when the target is dequeued","description":"When the current queued state equals target, return its stored distance.","commonMistakes":["Comparing target to the move count instead of the state","Returning -1 when the target is found"],"hint":"After reading state and steps from the queue, compare state to target and return steps.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"returns_terminal_result_during_frontier_expansion","scope":"target-return","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Stop BFS as soon as the dequeued lock state is the target.","doneWhen":"The current queued state is compared with target, and the carried distance is returned on match.","shouldFailWhen":"The code returns a constant, compares the target to the distance, or keeps expanding after target is dequeued.","roles":["current state","target state","carried distance"],"mustProve":["The target match returns the distance carried by the dequeued queue entry."],"mustNotAccept":["Returning -1 when the target is found.","Checking the distance value against target."],"proofSnippets":[{"id":"py-open-lock-return-target","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1\n            if state == target:\n                return steps"}]}},{"id":"filter-neighbors","title":"Filter and mark valid neighbors","description":"Generate one-turn states, reject dead or already-seen combinations, and mark accepted states before enqueueing.","commonMistakes":["Checking deadends but not visited states","Marking a state after enqueueing duplicates","Generating strings that are not one wheel turn away"],"hint":"After deriving next_state, require it to be outside both dead and seen, then add it to seen before it can be queued.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"checks_set_membership","scope":"membership-check","readMode":"set-membership-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"writes_set_membership_state","scope":"add-edge","readMode":"set-membership-value-query-v1"}]}]},"semanticSpec":{"intent":"Use membership state to filter invalid or repeated lock states before they enter the BFS frontier.","doneWhen":"This step is done when each generated neighbor is checked against dead and seen state, then marked seen once accepted.","shouldFailWhen":"This step should fail if neighbors are generated but deadends or repeats can still enter the search.","roles":["deadend set","seen set","neighbor state"],"mustProve":["Generated neighbors are checked against membership state.","Accepted neighbors are written into the seen state.","The membership guard happens before queue insertion."],"mustNotAccept":["Generating neighbors without a deadend check.","Generating neighbors without a visited check.","Adding duplicates to the BFS frontier."],"equivalentVariants":["Use a set for deadends and a set for seen states.","Use any equivalent membership structure that prevents dead or repeated states from being processed."],"proofSnippets":[{"id":"py-open-lock-filter-and-mark-neighbors","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1\n            if state == target:\n                return steps\n            for i in range(4):\n                digit = int(state[i])\n                for move in [-1, 1]:\n                    next_digit = (digit + move) % 10\n                    next_state = state[:i] + str(next_digit) + state[i + 1:]\n                    if next_state not in dead and next_state not in seen:\n                        seen.add(next_state)"}]}},{"id":"expand-neighbors","title":"Complete BFS neighbor expansion","description":"Generate one-turn neighbors and enqueue each valid unseen state with the next distance.","commonMistakes":["Missing backward turns","Forgetting modulo wraparound","Enqueuing deadends"],"hint":"For each of four positions, try -1 and +1, filter by dead and seen, then enqueue the accepted next state.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"distance-neighbors","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Derive and enqueue valid neighboring lock states from the current state.","doneWhen":"The nested neighbor loops generate next states and append unseen valid states to the queue with steps + 1.","shouldFailWhen":"The code does not expand neighbors from the dequeued state.","roles":["current state","neighbor state","queue"],"mustProve":["The solution expands frontier neighbors."],"mustNotAccept":["Adding arbitrary states that are not one wheel turn away."],"proofSnippets":[{"id":"py-open-lock-expand-neighbors","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1\n            if state == target:\n                return steps\n            for i in range(4):\n                digit = int(state[i])\n                for move in [-1, 1]:\n                    next_digit = (digit + move) % 10\n                    next_state = state[:i] + str(next_digit) + state[i + 1:]\n                    if next_state not in dead and next_state not in seen:\n                        seen.add(next_state)\n                        queue.append((next_state, steps + 1))"}]}},{"id":"return-unreachable","title":"Return -1 when BFS exhausts","description":"If the queue empties without finding target, return -1.","commonMistakes":["Returning 0 when no route exists","Falling off the function without an unreachable result"],"hint":"Place return -1 after the while loop, not inside the neighbor loop.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"returns_terminal_bfs_result","scope":"unreachable-return","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Report that target cannot be reached once BFS has no states left to process.","doneWhen":"A direct return -1 runs after the frontier loop finishes.","shouldFailWhen":"The code returns a non-negative value or has no unreachable return after the loop.","roles":["frontier queue","unreachable result"],"mustProve":["An exhausted BFS frontier returns -1."],"mustNotAccept":["Returning -1 before all queued states are processed.","Returning 0 when target was not reached."],"proofSnippets":[{"id":"py-open-lock-return-unreachable","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1\n            if state == target:\n                return steps\n            for i in range(4):\n                digit = int(state[i])\n                for move in [-1, 1]:\n                    next_digit = (digit + move) % 10\n                    next_state = state[:i] + str(next_digit) + state[i + 1:]\n                    if next_state not in dead and next_state not in seen:\n                        seen.add(next_state)\n                        queue.append((next_state, steps + 1))\n        return -1"}]}}],"slides":[{"id":"opener","kind":"info","chapter":"The lock","eyebrow":"Read the problem","title":"Turn four wheels to the target in the fewest moves","workspacePanel":"problem","body":["A lock has four wheels, each showing one digit. One move turns a single wheel up or down by one, and 0 wraps to 9 and 9 wraps to 0. Some combinations are deadends you may never land on. Starting from \"0000\", the question asks for the fewest moves that reach target, or -1 when every route is blocked.","Moves branch and can return to combinations already seen. Exploring combinations by distance makes the first arrival at target the shortest valid route."]},{"id":"brute-force","kind":"code-trace","source":"brute-force","chapter":"The slow way","eyebrow":"Start naive","title":"Chase one route to its end before trying the next","summary":"The first idea that works is to follow a single route as far as it goes: from \"0000\", turn a wheel, then turn again from there, keeping the move count of the best route that lands on target. Each route remembers the states it has already used so it never loops, so the search does finish and does find the minimum, but only after grinding through route after route. Watch how deep one route runs before it ever sees \"0002\".","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def openLock(deadends: list[str], target: str) -> int:\n    def turn(state: str, index: int, delta: int) -> str:\n        digit = (int(state[index]) + delta) % 10\n        return state[:index] + str(digit) + state[index + 1:]\n    dead = set(deadends)\n    stack: list[tuple[str, int, list[str]]] = [(\"0000\", 0, [\"0000\"])]\n    best = -1\n    while stack:\n        state, moves, path = stack.pop()\n        if state == target:\n            if best == -1 or moves < best:\n                best = moves\n            continue\n        for i in range(4):\n            for d in (-1, 1):\n                nxt = turn(state, i, d)\n                if nxt not in dead and nxt not in path:\n                    stack.append((nxt, moves + 1, path + [nxt]))\n    return best","steps":[{"id":"b1","title":"Dive from \"0000\" into \"0010\", then \"0011\"","codeLine":18,"summary":"The walk takes the first route it finds: \"0000\" -> \"0010\" -> \"0011\", three states deep and still not at \"0002\".","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0010"],["0001","0011"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0011","highlighted":["0010"],"visited":["0000","0010","0011"],"activeEdges":[["0010","0011"]]}}},{"id":"b2","title":"Keep diving: \"0011\" -> \"0012\" -> \"0002\"","codeLine":18,"summary":"From \"0011\" the walk picks \"0012\", then \"0002\", landing on target after four moves down this one branch. Each push records the state in this route's path so the dive never loops back on itself.","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0010"],["0001","0011"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0002","highlighted":["0012"],"visited":["0000","0010","0011","0012","0002"],"activeEdges":[["0012","0002"]]}}},{"id":"b3","title":"Record 4, keep it as the best so far, then unwind","codeLine":12,"summary":"It keeps 4 as the best route found so far, then backs out to \"0000\" and tries \"0001\" next, re-walking states it has already turned through under a different order.","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0010"],["0001","0011"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0001","highlighted":["0000"],"visited":["0000","0001"],"activeEdges":[["0000","0001"]]}}},{"id":"b4","title":"\"0001\" reaches \"0002\" the long way too","codeLine":10,"summary":"The \"0001\" route also reaches \"0002\", but only after revisiting \"0011\" and \"0012\" again. The walk explores full routes one after another, with no sense of which is shortest.","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0010"],["0001","0011"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0002","highlighted":["0012"],"visited":["0000","0001","0011","0012","0002"],"activeEdges":[["0012","0002"]]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function turn(state, index, delta) {\n    const digit = floorModulo((Number.parseInt(state[index], 10) + delta), 10);\n    return ((state.slice(0, index) + String(digit)) + state.slice((index + 1)));\n}\nconst dead = new Set(deadends);\nconst stack = [[\"0000\", 0, [\"0000\"]]];\nlet best = -1;\nwhile (stack.length > 0) {\n    const [state, moves, path] = stack.pop();\n    if (state === target) {\n        if (best === -1 || moves < best) {\n            best = moves;\n        }\n        continue;\n    }\n    for (let i = 0; i < 4; i++) {\n        for (const d of [-1, 1]) {\n            const nxt = turn(state, i, d);\n            if (!dead.has(nxt) && !path.includes(nxt)) {\n                stack.push([nxt, (moves + 1), path.concat([nxt])]);\n            }\n        }\n    }\n}\nreturn best;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14,"14":16,"15":17,"16":18,"17":19,"18":20,"19":25},"statementBundles":{"4":{"startLine":3,"endLine":4},"12":{"startLine":12,"endLine":13},"13":{"startLine":14,"endLine":15},"18":{"startLine":20,"endLine":24}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function turn(state: string, index: number, delta: number): string {\n    const digit = floorModulo((Number.parseInt(state[index], 10) + delta), 10);\n    return ((state.slice(0, index) + String(digit)) + state.slice((index + 1)));\n}\nconst dead = new Set(deadends);\nconst stack: Array<[string, number, Array<string>]> = [[\"0000\", 0, [\"0000\"]]];\nlet best = -1;\nwhile (stack.length > 0) {\n    const [state, moves, path] = stack.pop()!;\n    if (state === target) {\n        if (best === -1 || moves < best) {\n            best = moves;\n        }\n        continue;\n    }\n    for (let i = 0; i < 4; i++) {\n        for (const d of [-1, 1]) {\n            const nxt = turn(state, i, d);\n            if (!dead.has(nxt) && !path.includes(nxt)) {\n                stack.push([nxt, (moves + 1), path.concat([nxt])]);\n            }\n        }\n    }\n}\nreturn best;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14,"14":16,"15":17,"16":18,"17":19,"18":20,"19":25},"statementBundles":{"4":{"startLine":3,"endLine":4},"12":{"startLine":12,"endLine":13},"13":{"startLine":14,"endLine":15},"18":{"startLine":20,"endLine":24}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static String turn(String state, int index, int delta) {\n    int digit = Math.floorMod((Integer.parseInt(String.valueOf(state.charAt(index))) + delta), 10);\n    return (String)((state.substring(0, index) + String.valueOf(digit)) + state.substring((index + 1), state.length()));\n}\n\nrecord StackItem(String state, int moves, List<String> path) {}\nSet<String> dead = new HashSet<String>(deadends);\nList<StackItem> stack = new ArrayList<>(Arrays.asList(new StackItem(\"0000\", 0, new ArrayList<>(List.of(\"0000\")))));\nint best = -1;\nwhile (!stack.isEmpty()) {\n    StackItem item = stack.remove(stack.size() - 1);\n    String state = item.state();\n    int moves = item.moves();\n    List<String> path = item.path();\n    if (Objects.equals(state, target)) {\n        if (best == -1 || moves < best) {\n            best = moves;\n        }\n        continue;\n    }\n    for (int i = 0; i < 4; i++) {\n        for (Integer d : new ArrayList<>(List.of(-1, 1))) {\n            String nxt = turn(state, i, d);\n            if ((!dead.contains(nxt) && !path.contains(nxt))) {\n                List<String> nextPath = new ArrayList<>(path);\n                nextPath.add(nxt);\n                stack.add(new StackItem(nxt, (moves + 1), nextPath));\n            }\n        }\n    }\n}\nreturn best;","lineMap":{"3":2,"4":3,"5":7,"6":8,"7":9,"8":10,"9":11,"10":15,"11":16,"12":17,"13":19,"14":21,"15":22,"16":23,"17":24,"18":25,"19":32},"statementBundles":{"4":{"startLine":3,"endLine":6},"9":{"startLine":11,"endLine":14},"12":{"startLine":17,"endLine":18},"13":{"startLine":19,"endLine":20},"18":{"startLine":25,"endLine":31}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"string Turn(string state, int index, int delta) {\n    int digit = FloorModulo((int.Parse(state[index].ToString()) + delta), 10);\n    return state.Substring(0, index) + Convert.ToString(digit) + state.Substring(index + 1, (state.Length) - (index + 1));\n    return null;\n}\nHashSet<string> dead = new(deadends);\nList<(string, int, List<string>)> stack = new() { (\"0000\", 0, new List<string> { \"0000\" }) };\nint best = -1;\nwhile (stack.Count > 0) {\n    var (state, moves, path) = stack[stack.Count - 1];\n    stack.RemoveAt(stack.Count - 1);\n    if (state == target) {\n        if (best == -1 || moves < best) {\n            best = moves;\n        }\n        continue;\n    }\n    for (int i = 0; i < 4; i++) {\n        foreach (int d in new List<int> { -1, 1 }) {\n            string nxt = Turn(state, i, d);\n            if (!dead.Contains(nxt) && !path.Contains(nxt)) {\n                stack.Add((nxt, moves + 1, path.Concat(new List<string> { nxt }).ToList()));\n            }\n        }\n    }\n}\nreturn best;","lineMap":{"3":2,"4":3,"5":6,"6":7,"7":8,"8":9,"9":10,"10":12,"11":13,"12":14,"13":16,"14":18,"15":19,"16":20,"17":21,"18":22,"19":27},"statementBundles":{"4":{"startLine":3,"endLine":5},"9":{"startLine":10,"endLine":11},"12":{"startLine":14,"endLine":15},"13":{"startLine":16,"endLine":17},"18":{"startLine":22,"endLine":26}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"auto turn = [&]( string state, int index, int delta ) -> string {\n    int digit = floorModulo((stoi(string(1, state[index])) + delta), 10);\n    return ((string(state.begin() + 0, state.begin() + index) + to_string(digit)) + string(state.begin() + (index + 1), state.begin() + state.size()));\n};\nunordered_set<string> dead = unordered_set<string>(deadends.begin(), deadends.end());\nvector<tuple<string, int, vector<string>>> stack_{{\"0000\", 0, vector<string>{\"0000\"}}};\nint best = -1;\nwhile (!stack_.empty()) {\n    auto popped_item = stack_.back(); stack_.pop_back();\n    auto [state, moves, path] = popped_item;\n    if (state == target) {\n        if ((best == -1 || moves < best)) {\n            best = moves;\n        }\n        continue;\n    }\n    for (int i = 0; i < 4; i++) {\n        for (int d : vector<int>{-1, 1}) {\n            string nxt = turn(state, i, d);\n            if ((!dead.count(nxt) && !containsValue(path, nxt))) {\n                vector<string> next_path = path;\n                vector<string> right_values = vector<string>{nxt};\n                next_path.insert(next_path.end(), right_values.begin(), right_values.end());\n                stack_.push_back(tuple<string, int, vector<string>>{nxt, (moves + 1), next_path});\n            }\n        }\n    }\n}\nreturn best;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":11,"11":12,"12":13,"13":15,"14":17,"15":18,"16":19,"17":20,"18":21,"19":29},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":10},"12":{"startLine":13,"endLine":14},"13":{"startLine":15,"endLine":16},"18":{"startLine":21,"endLine":28}}}}}},{"id":"brute-cost","kind":"case-probe","chapter":"The slow way","eyebrow":"Count the work","title":"How many routes does the depth-first walk explore?","workspacePanel":"trace","summary":"Each state has up to eight neighbors, and the walk follows one all the way to a deadend or target before trying the next.","options":[{"id":"every-route","label":"Close to every distinct route through the states, which explodes as the reachable set grows","rationale":"Following every order branches at each state, so the number of routes explored balloons with how many states are reachable. The walk lands on target the long way first and only later stumbles onto the short route.","isCorrect":true},{"id":"one-per-state","label":"One route per state, so about as many routes as there are states","rationale":"Each state can branch into several routes. The walk re-enters the same states under many different orders, so the count is far larger than the number of states.","isCorrect":false},{"id":"shortest-first","label":"Just the shortest route, because going deep finds the nearest target first","rationale":"Diving commits to one branch to the bottom before trying alternatives, so it can land on target on a long route well before it ever sees the short one. Depth has no sense of nearest.","isCorrect":false}],"answer":"Close to every distinct route. The walk dives to the bottom of one route before trying the next, so it lands on target the long way first and re-treads the same states again and again before the shortest route appears. With up to 10000 distinct combinations in the lock graph, the route count can climb far beyond the 10000 states a search that visits each combination once would need."},{"id":"organize-by-distance","kind":"info","chapter":"The idea","eyebrow":"Reframe the search","title":"Stop chasing routes; organize states by distance","workspacePanel":"visualizer","body":["Route-chasing was hopeless: the same states get re-walked under endless orderings before the short route ever turns up. The fix is to stop thinking in routes at all and think in distance from \"0000\" instead.","Picture each combination as a node, with an edge between any two combinations one wheel-turn apart. The states one move from \"0000\" form a first ring, the states two moves away a second ring, and so on outward. The next question is what that layering buys us: if we expand the rings in order, when does target first show up?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0000","highlighted":["0001","0009","0010"],"activeEdges":[["0000","0001"],["0000","0009"],["0000","0010"]]}}}]}},{"id":"discover-bfs","kind":"case-probe","chapter":"The idea","eyebrow":"Find the shortcut","title":"If you spread outward one ring at a time, when do you first reach target?","workspacePanel":"visualizer","summary":"Picture each combination as a node, with an edge between any two combinations one wheel-turn apart. From \"0000\", the states one move away form a first ring, the states two moves away a second ring, and so on.","options":[{"id":"first-reach","label":"The first ring that includes target is its move count, and you can stop there","rationale":"Ring k holds exactly the states reachable in k moves and no fewer. So the first ring that contains target is the fewest moves that reach it, and you can stop the moment it appears. Here target shows up on ring 4.","isCorrect":true},{"id":"must-finish","label":"You must expand every ring to the end, then compare all the routes that reached target","rationale":"Outer rings are always at least as far as inner ones, so once a ring contains target nothing later can beat it. Expanding further only finds equal or longer routes.","isCorrect":false},{"id":"depends-order","label":"It depends which neighbor inside a ring you expand first","rationale":"Every state in the same ring sits the same number of moves from the start, so the order within a ring does not change when target first appears. The ring number alone fixes the distance.","isCorrect":false}],"answer":"The first ring that contains target gives the answer. Ring k is exactly the states reachable in k moves, so the moment target shows up you have the fewest moves, and no later ring can do better. Spreading outward ring by ring is breadth-first search, and the first arrival is the shortest route.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0000","highlighted":["0010"],"activeEdges":[["0000","0010"]]}}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the route","title":"How should the search reach target?","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"dfs-search","name":"Depth-first search","summary":"Dive down one route to its end, then back out and try the next route.","decisionReason":"Going deep commits to a single route and can land on target the long way first, so it cannot certify the route it found is shortest until it has exhausted the other routes. That is the same route-chasing blow-up the slow baseline showed.","complexity":{"time":"O(routes)","space":"O(10000)"},"tradeoffs":["First arrival on target is not guaranteed shortest, so it must keep searching to confirm the minimum."],"isOptimal":false},{"id":"bfs-shortest-path","name":"BFS shortest path","summary":"Spread outward in FIFO distance rings from 0000 and stop the instant target is dequeued.","decisionReason":"FIFO order processes every state at distance k before any at distance k+1, so the first time target comes off the queue is already the fewest moves and the search can stop. Each state is visited once.","complexity":{"time":"O(10000)","space":"O(10000)"},"tradeoffs":["First arrival on target is final, so it visits each of the 10000 states at most once."],"isOptimal":true}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]]}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace it","eyebrow":"Watch it move","title":"Spread from \"0000\", one ring per step","workspacePanel":"visualizer","body":["Keep a queue of states to expand and a seen record of states already reached. Seed the queue with \"0000\" at zero moves and mark \"0000\" seen. The queue always holds the current frontier of states.","Pull the oldest state off the queue, look at every state one wheel-turn away, and for each one that is neither a deadend nor already seen, mark it and add it at one more than the current move count. The instant a state equals target, that move count is the answer. Watch the frontier sweep outward from \"0000\" toward \"0002\", stepping over the deadend \"0001\"."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0000","visited":["0000"]}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace it","eyebrow":"Trace the search","title":"Sweep from \"0000\" out to \"0002\"","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"expand-start","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0000","highlighted":["0009","0010"],"visited":["0000","0009","0010"],"activeEdges":[["0000","0009"],["0000","0010"]]}}},{"id":"expand-ring1","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0010","highlighted":["0011"],"visited":["0000","0009","0010","0011"],"activeEdges":[["0010","0011"]]}}},{"id":"expand-ring2","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0011","highlighted":["0012"],"visited":["0000","0009","0010","0011","0012"],"activeEdges":[["0011","0012"]]}}},{"id":"reach-target","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0012","highlighted":["0002"],"visited":["0000","0009","0010","0011","0012","0002"],"activeEdges":[["0012","0002"]]}}}]},"beats":[{"id":"expand-start","title":"\"0000\"'s neighbor \"0001\" is a deadend. Which states enter the queue?","summary":"The queue holds (\"0000\", 0).","prompt":"The first expansion inspects one dead neighbor and two open neighbors.","options":[{"id":"skip-dead","label":"\"0009\" and \"0010\" at 1 move; \"0001\" is skipped","rationale":"\"0001\" is a deadend, so it never enters the queue. The other neighbors are one move past \"0000\" (0 moves), so they are marked seen and queued at 1.","isCorrect":true},{"id":"all-three","label":"All three, including \"0001\", at 1 move","rationale":"\"0001\" is a deadend the lock may never land on, so it is filtered out before it can be queued. Only the non-dead neighbors enter.","isCorrect":false},{"id":"zero","label":"\"0009\" and \"0010\" at 0 moves, same as \"0000\"","rationale":"Reusing \"0000\"'s count would mean the neighbors cost no move, but each took one wheel-turn to reach. They enter at one more than the state they came from.","isCorrect":false}],"answer":"\"0009\" and \"0010\" enter at 1 move; \"0001\" is a deadend and is skipped. The frontier has stepped one ring out, around the blocked combination."},{"id":"expand-ring1","title":"Expanding \"0010\" reaches \"0011\". At what move count is it queued?","summary":"We pull (\"0010\", 1). Its unseen, non-dead neighbor is \"0011\".","prompt":"\"0010\" is at 1 move, and \"0011\" is still unseen.","options":[{"id":"two","label":"2 moves, one past \"0010\"","rationale":"\"0011\" is one move past \"0010\" (1 move), so it is marked seen and queued at 1 + 1 = 2.","isCorrect":true},{"id":"one","label":"1 move, the same as \"0010\"","rationale":"\"0011\" took a wheel-turn to reach from \"0010\", so it cannot share its count. Each neighbor enters at one more than the state it came from.","isCorrect":false},{"id":"four","label":"4 moves, the final answer","rationale":"The answer is only known once target appears. \"0011\" is just two rings out; its stored count is 2.","isCorrect":false}],"answer":"2 moves. \"0011\" is one move past \"0010\" (1 move), so it is marked seen and queued as (\"0011\", 2)."},{"id":"expand-ring2","title":"After expanding \"0011\" to \"0012\", is the search finished?","summary":"We pull (\"0011\", 2) and reach \"0012\".","prompt":"\"0011\" is at 2 moves, and \"0012\" is its unseen neighbor.","options":[{"id":"not-yet","label":"Not yet: \"0012\" is queued at 3, and target has not been reached","rationale":"\"0012\" is one move past \"0011\" (2 moves), so it enters at 3. We have not yet inspected a neighbor equal to \"0002\", so the search continues one more ring.","isCorrect":true},{"id":"done","label":"Done: \"0012\" is close to \"0002\", so stop here","rationale":"Closeness is not the test. \"0012\" is queued at 3, and the search only stops when it actually inspects a neighbor equal to target.","isCorrect":false},{"id":"restart","label":"Restart from target, searching backward","rationale":"A single forward sweep from \"0000\" already finds the shortest route. There is no need to search from the other end.","isCorrect":false}],"answer":"Not finished. \"0012\" is one move past \"0011\" (2 moves), so it is queued as (\"0012\", 3). Target is still one ring away, so the search keeps going."},{"id":"reach-target","title":"Expanding \"0012\" reaches \"0002\". What move count do we return?","summary":"We pull (\"0012\", 3). One of its neighbors is \"0002\", the target.","prompt":"\"0012\" is at 3 moves, and its neighbor \"0002\" equals target.","options":[{"id":"four","label":"4 moves, one more than 3","rationale":"\"0002\" is one move past \"0012\" (3 moves), so the route \"0000\" -> \"0010\" -> \"0011\" -> \"0012\" -> \"0002\" takes 3 + 1 = 4 moves. The first arrival at target is the shortest route.","isCorrect":true},{"id":"three","label":"3 moves, since \"0012\" was already at 3","rationale":"\"0002\" is one move beyond \"0012\", so it costs one more. Returning 3 would forget to count the final turn onto target.","isCorrect":false},{"id":"two","label":"2 moves, the direct distance from \"0000\" to \"0002\"","rationale":"The direct two-move route runs through the deadend \"0001\", which the search may never use. The shortest legal route detours and takes 4.","isCorrect":false}],"answer":"4 moves. \"0002\" is one move past \"0012\" (3 moves), so we return 3 + 1 = 4. Because this is the first ring to contain target, that 4-move route is the shortest one that avoids the deadend."}]},{"id":"visited-pitfall","kind":"pitfall","chapter":"Trace it","eyebrow":"Spot the trap","title":"Could you mark a state seen when you pull it, instead of when you queue it?","workspacePanel":"trace","summary":"Marking seen at dequeue time looks equivalent: every state still gets marked, and the target check still fires. But between queueing a state and pulling it, watch what a combination reachable from two frontier states does to the queue.","pitfall":"The code below adds each non-dead neighbor to the queue and only marks a state seen when it is later pulled, so a state reachable from two frontier states is queued more than once.","whyItMatters":"\"0011\" is one turn from both \"0001\" and \"0010\". Both are pulled before \"0011\" is, and neither has marked \"0011\" yet, so each queues its own copy of (\"0011\", 2). Both copies are later pulled and each re-adds \"0011\"'s neighbors, and on the full lock the queue swells with duplicates of every state that has more than one route in. Mark a state seen the moment you queue it, so it is added exactly once.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def openLock(deadends: list[str], target: str) -> int:\n    def turn(state: str, index: int, delta: int) -> str:\n        digit = (int(state[index]) + delta) % 10\n        return state[:index] + str(digit) + state[index + 1:]\n    dead = set(deadends)\n    queue: list[tuple[str, int]] = [(\"0000\", 0)]\n    seen: set[str] = set()\n    head = 0\n    while head < len(queue):\n        state, moves = queue[head]\n        head += 1\n        seen.add(state)\n        if state == target:\n            return moves\n        for i in range(4):\n            for d in (-1, 1):\n                nxt = turn(state, i, d)\n                if nxt not in dead and nxt not in seen:\n                    queue.append((nxt, moves + 1))\n    return -1","steps":[{"id":"q-0001","title":"Pull \"0001\" and queue its neighbor \"0011\"","codeLine":19,"summary":"\"0001\" is pulled at 1 move and marked seen now. \"0011\" is not yet seen, so it is queued as (\"0011\", 2). The frontier now holds \"0010\" (still waiting) and one copy of \"0011\".","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011 (queued x1)"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0010"],["0001","0011"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0001","queue":["0010","0011"],"highlighted":["0011"],"activeEdges":[["0001","0011"]]}}},{"id":"q-0010","title":"Pull \"0010\" and queue \"0011\" a second time","codeLine":19,"summary":"\"0010\" is pulled, also at 1 move. \"0011\" was queued but never marked seen, so the seen check passes again and \"0011\" is queued a second time. The frontier now carries two copies of \"0011\".","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011 (queued x2)"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0010"],["0001","0011"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0010","queue":["0011","0011"],"highlighted":["0011"],"activeEdges":[["0010","0011"]]}}},{"id":"q-dup","title":"Both copies of \"0011\" get expanded","codeLine":19,"summary":"The first \"0011\" is pulled and queues \"0012\". Then the duplicate \"0011\" is pulled and queues \"0012\" all over again, so the frontier now carries two copies of \"0012\". The redundant work multiplies down every later ring.","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011 (queued x2)"},{"id":"0012","label":"0012 (queued x2)"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0010"],["0001","0011"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0011","queue":["0012","0012"],"highlighted":["0012"],"activeEdges":[["0011","0012"]]}}},{"id":"q-bloat","title":"The queue fills with states already reached","codeLine":19,"summary":"Every state with more than one route in gets queued once per route, and each duplicate re-adds its own neighbors. Here \"0011\" and \"0012\" each sit in the frontier twice; on the full 10000-state lock the queue bloats and the search re-walks states it already passed. Wrong shape, even when an answer eventually appears.","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011 (queued x2)"},{"id":"0012","label":"0012 (queued x2)"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0010"],["0001","0011"],["0010","0011"],["0011","0012"],["0012","0002"]],"queue":["0011","0012"],"visited":["0000","0001","0010"]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function turn(state, index, delta) {\n    const digit = floorModulo((Number.parseInt(state[index], 10) + delta), 10);\n    return ((state.slice(0, index) + String(digit)) + state.slice((index + 1)));\n}\nconst dead = new Set(deadends);\nconst queue = [[\"0000\", 0]];\nconst seen = new Set();\nlet head = 0;\nwhile (head < queue.length) {\n    const [state, moves] = queue[head];\n    head++;\n    seen.add(state);\n    if (state === target) {\n        return moves;\n    }\n    for (let i = 0; i < 4; i++) {\n        for (const d of [-1, 1]) {\n            const nxt = turn(state, i, d);\n            if (!dead.has(nxt) && !seen.has(nxt)) {\n                queue.push([nxt, (moves + 1)]);\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":16,"16":17,"17":18,"18":19,"19":20,"20":25},"statementBundles":{"4":{"startLine":3,"endLine":4},"14":{"startLine":14,"endLine":15},"19":{"startLine":20,"endLine":24}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function turn(state: string, index: number, delta: number): string {\n    const digit = floorModulo((Number.parseInt(state[index], 10) + delta), 10);\n    return ((state.slice(0, index) + String(digit)) + state.slice((index + 1)));\n}\nconst dead = new Set(deadends);\nconst queue: Array<[string, number]> = [[\"0000\", 0]];\nconst seen: Set<string> = new Set();\nlet head = 0;\nwhile (head < queue.length) {\n    const [state, moves] = queue[head];\n    head++;\n    seen.add(state);\n    if (state === target) {\n        return moves;\n    }\n    for (let i = 0; i < 4; i++) {\n        for (const d of [-1, 1]) {\n            const nxt = turn(state, i, d);\n            if (!dead.has(nxt) && !seen.has(nxt)) {\n                queue.push([nxt, (moves + 1)]);\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":16,"16":17,"17":18,"18":19,"19":20,"20":25},"statementBundles":{"4":{"startLine":3,"endLine":4},"14":{"startLine":14,"endLine":15},"19":{"startLine":20,"endLine":24}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static String turn(String state, int index, int delta) {\n    int digit = Math.floorMod((Integer.parseInt(String.valueOf(state.charAt(index))) + delta), 10);\n    return (String)((state.substring(0, index) + String.valueOf(digit)) + state.substring((index + 1), state.length()));\n}\n\nrecord QueueItem(String state, int moves) {}\nSet<String> dead = new HashSet<String>(deadends);\nList<QueueItem> queue = new ArrayList<>(Arrays.asList(new QueueItem(\"0000\", 0)));\nSet<String> seen = new HashSet<String>();\nint head = 0;\nwhile (head < queue.size()) {\n    QueueItem item = queue.get(head);\n    String state = item.state();\n    int moves = item.moves();\n    head++;\n    seen.add(state);\n    if (Objects.equals(state, target)) {\n        return moves;\n    }\n    for (int i = 0; i < 4; i++) {\n        for (Integer d : new ArrayList<>(List.of(-1, 1))) {\n            String nxt = turn(state, i, d);\n            if ((!dead.contains(nxt) && !seen.contains(nxt))) {\n                queue.add(new QueueItem(nxt, (moves + 1)));\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"3":2,"4":3,"5":7,"6":8,"7":9,"8":10,"9":11,"10":12,"11":15,"12":16,"13":17,"14":18,"15":20,"16":21,"17":22,"18":23,"19":24,"20":29},"statementBundles":{"4":{"startLine":3,"endLine":6},"10":{"startLine":12,"endLine":14},"14":{"startLine":18,"endLine":19},"19":{"startLine":24,"endLine":28}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"string Turn(string state, int index, int delta) {\n    int digit = FloorModulo((int.Parse(state[index].ToString()) + delta), 10);\n    return state.Substring(0, index) + Convert.ToString(digit) + state.Substring(index + 1, (state.Length) - (index + 1));\n    return null;\n}\nHashSet<string> dead = new(deadends);\nList<(string, int)> queue = new() { (\"0000\", 0) };\nHashSet<string> seen = new();\nint head = 0;\nwhile (head < queue.Count) {\n    var (state, moves) = queue[head];\n    head++;\n    seen.Add(state);\n    if (state == target) {\n        return moves;\n    }\n    for (int i = 0; i < 4; i++) {\n        foreach (int d in new List<int> { -1, 1 }) {\n            string nxt = Turn(state, i, d);\n            if (!dead.Contains(nxt) && !seen.Contains(nxt)) {\n                queue.Add((nxt, moves + 1));\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"3":2,"4":3,"5":6,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15,"15":17,"16":18,"17":19,"18":20,"19":21,"20":26},"statementBundles":{"4":{"startLine":3,"endLine":5},"14":{"startLine":15,"endLine":16},"19":{"startLine":21,"endLine":25}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"auto turn = [&]( string state, int index, int delta ) -> string {\n    int digit = floorModulo((stoi(string(1, state[index])) + delta), 10);\n    return ((string(state.begin() + 0, state.begin() + index) + to_string(digit)) + string(state.begin() + (index + 1), state.begin() + state.size()));\n};\nunordered_set<string> dead = unordered_set<string>(deadends.begin(), deadends.end());\nvector<pair<string, int>> queue{{\"0000\", 0}};\nunordered_set<string> seen;\nsize_t head = 0;\nwhile (head < queue.size()) {\n    auto [state, moves] = queue[static_cast<int>(head)];\n    head++;\n    seen.insert(state);\n    if (state == target) {\n        return moves;\n    }\n    for (int i = 0; i < 4; i++) {\n        for (int d : vector<int>{-1, 1}) {\n            string nxt = turn(state, i, d);\n            if ((!dead.count(nxt) && !seen.count(nxt))) {\n                queue.push_back(pair<string, int>{nxt, (moves + 1)});\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":16,"16":17,"17":18,"18":19,"19":20,"20":25},"statementBundles":{"4":{"startLine":3,"endLine":4},"14":{"startLine":14,"endLine":15},"19":{"startLine":20,"endLine":24}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Spreading ring by ring with a seen set returns the shortest route, and the first ring to reach target is the answer.","The sweep assumes the start is a legal place to stand and that the move count lines up with rings. Push on both before you code: feed it an input where \"0000\" itself is a deadend, and one where target is \"0000\"."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0000","visited":["0000"]}}}]}},{"id":"edge-start-dead","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"\"0000\" is itself a deadend: what is returned?","workspacePanel":"visualizer","summary":"deadends now contains \"0000\", the very combination the lock starts on.","options":[{"id":"neg-one","label":"Return -1, because the start is a state the lock may never occupy","rationale":"Every state in a route, including the first, must avoid the deadends. If \"0000\" is forbidden, the search can never even begin, so no route exists and the answer is -1. A check before seeding the queue catches this.","isCorrect":true},{"id":"zero","label":"Return 0, since we start on \"0000\" anyway","rationale":"Returning 0 would claim the lock is already open at a forbidden combination. A deadend start means the lock cannot legally sit there, so the answer is -1, not 0.","isCorrect":false},{"id":"skip","label":"Skip \"0000\" and start from its neighbors","rationale":"There is nowhere legal to start from. If the very first state is forbidden, no first move is allowed, so the search returns -1 rather than inventing a different origin.","isCorrect":false}],"answer":"Return -1. The first state must also avoid the deadends, and a forbidden \"0000\" leaves no legal place to begin. A membership check before seeding the queue returns -1 with no rings expanded.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"graph":{"nodes":[{"id":"0000","label":"0000 (deadend)"}],"edges":[]}}}]}},{"id":"edge-target-start","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"target is \"0000\": how many moves?","workspacePanel":"visualizer","summary":"The lock starts on \"0000\" and target is also \"0000\", with \"0000\" not among the deadends.","options":[{"id":"zero","label":"0 moves, because the start already equals target","rationale":"The first state pulled from the queue is \"0000\" at 0 moves, and it already equals target, so the search returns 0 before turning any wheel. This is why the target check runs on each state as it is pulled.","isCorrect":true},{"id":"one","label":"1 move, since at least one turn is always needed","rationale":"No turn is needed when the lock already shows target. The move count seeded at 0 is returned as-is, so the answer is 0.","isCorrect":false},{"id":"eight","label":"8 moves, to cycle every wheel back to itself","rationale":"Returning to the same combination costs nothing; the lock is already there. The search returns 0 immediately.","isCorrect":false}],"answer":"0 moves. \"0000\" is the first state pulled, and it already equals target, so the search returns its stored count of 0 before any wheel turns. Checking target as each state comes off the queue handles this without a special case.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"graph":{"nodes":[{"id":"0000","label":"0000"}],"edges":[],"current":"0000","visited":["0000"]}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"Guard the dead start, then spread outward ring by ring, marking each state once.","body":["First reject the impossible case: if \"0000\" is a deadend, return -1 before any search. Then seed the queue with \"0000\" at zero moves and mark it seen, keeping the deadends as a set to test membership quickly.","Then sweep: pull the oldest state, generate each one-turn neighbor by moving a single wheel up or down with wraparound, and for every neighbor that is neither dead nor already seen, mark it and queue it at one more than the current count. Finish when a state equals target, or return -1 once the queue empties."],"ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"graph":{"nodes":[{"id":"0000","label":"0000"},{"id":"0001","label":"0001"},{"id":"0009","label":"0009"},{"id":"0010","label":"0010"},{"id":"0011","label":"0011"},{"id":"0012","label":"0012"},{"id":"0002","label":"0002"}],"edges":[["0000","0001"],["0000","0009"],["0000","0010"],["0001","0011"],["0001","0002"],["0010","0011"],["0011","0012"],["0012","0002"]],"current":"0000","visited":["0000"]}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the shortest-route search","eyebrow":"Code the rule","summary":"Build the BFS in the same order: reject a blocked start, seed the queue, generate one-turn neighbors, skip dead or seen states, and return the first target distance.","workspacePanel":"code","checkpoints":[{"id":"guard-start-dead","title":"Reject a blocked start","description":"If \"0000\" is a deadend, return -1 before starting BFS.","commonMistakes":["Starting BFS from a forbidden state","Returning 0 when the start is blocked"],"hint":"Build deadend membership, then check whether \"0000\" is blocked before seeding the queue.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"short_circuits_trivial_case","scope":"start-dead","readMode":"bfs-queue-value-query-v1","expected":{"seedLiteral":"0000","unreachableSentinel":-1}}]},"semanticSpec":{"intent":"Stop immediately when the starting lock state is forbidden.","doneWhen":"The code checks deadend membership for \"0000\" and returns -1 before traversal.","shouldFailWhen":"The code starts BFS from \"0000\" even when it is a deadend or returns the wrong value.","roles":["deadend membership","start state","blocked return"],"mustProve":["The blocked start state returns -1 before BFS begins."],"mustNotAccept":["Checking some other state before BFS.","Returning a non-negative distance for a blocked start."],"proofSnippets":[{"id":"py-open-lock-guard-start-dead","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1"}]}},{"id":"init-queue","title":"Initialize BFS state","description":"Seed the BFS queue with \"0000\" at distance 0.","commonMistakes":["Starting BFS even when 0000 is dead","Seeding the queue without the starting distance"],"hint":"The queue starts with (\"0000\", 0).","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"initializes_frontier_and_aux_state","scope":"init-distance-queue","readMode":"bfs-queue-value-query-v1","expected":{"seedLiteral":"0000"}}]},"semanticSpec":{"intent":"Seed the BFS frontier from the starting lock state.","doneWhen":"The queue contains (\"0000\", 0) before traversal.","shouldFailWhen":"The code has no queue frontier or does not seed the starting distance.","roles":["queue","start state","distance"],"mustProve":["The solution initializes BFS frontier and auxiliary state."],"mustNotAccept":["A traversal with no visited state."],"proofSnippets":[{"id":"py-open-lock-init-queue","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]"}]}},{"id":"bfs-loop","title":"Drive the queue loop","description":"Process states while the BFS frontier still has queued entries.","commonMistakes":["Using a stack-style traversal","Forgetting to advance the queue head"],"hint":"Continue while the head position is before the end of the queue, then increment head after reading the current state.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"loops_while_frontier_non_empty","scope":"bfs-loop","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Consume the BFS frontier in FIFO order.","doneWhen":"The loop reads queued states and advances the frontier pointer.","shouldFailWhen":"The frontier is never consumed or the loop is not queue-driven.","roles":["queue","head index"],"mustProve":["The solution loops while the frontier is non-empty."],"mustNotAccept":["A loop unrelated to queued lock states."],"proofSnippets":[{"id":"py-open-lock-bfs-loop","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1"}]}},{"id":"return-target","title":"Return when the target is dequeued","description":"When the current queued state equals target, return its stored distance.","commonMistakes":["Comparing target to the move count instead of the state","Returning -1 when the target is found"],"hint":"After reading state and steps from the queue, compare state to target and return steps.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"returns_terminal_result_during_frontier_expansion","scope":"target-return","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Stop BFS as soon as the dequeued lock state is the target.","doneWhen":"The current queued state is compared with target, and the carried distance is returned on match.","shouldFailWhen":"The code returns a constant, compares the target to the distance, or keeps expanding after target is dequeued.","roles":["current state","target state","carried distance"],"mustProve":["The target match returns the distance carried by the dequeued queue entry."],"mustNotAccept":["Returning -1 when the target is found.","Checking the distance value against target."],"proofSnippets":[{"id":"py-open-lock-return-target","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1\n            if state == target:\n                return steps"}]}},{"id":"filter-neighbors","title":"Filter and mark valid neighbors","description":"Generate one-turn states, reject dead or already-seen combinations, and mark accepted states before enqueueing.","commonMistakes":["Checking deadends but not visited states","Marking a state after enqueueing duplicates","Generating strings that are not one wheel turn away"],"hint":"After deriving next_state, require it to be outside both dead and seen, then add it to seen before it can be queued.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"checks_set_membership","scope":"membership-check","readMode":"set-membership-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"writes_set_membership_state","scope":"add-edge","readMode":"set-membership-value-query-v1"}]}]},"semanticSpec":{"intent":"Use membership state to filter invalid or repeated lock states before they enter the BFS frontier.","doneWhen":"This step is done when each generated neighbor is checked against dead and seen state, then marked seen once accepted.","shouldFailWhen":"This step should fail if neighbors are generated but deadends or repeats can still enter the search.","roles":["deadend set","seen set","neighbor state"],"mustProve":["Generated neighbors are checked against membership state.","Accepted neighbors are written into the seen state.","The membership guard happens before queue insertion."],"mustNotAccept":["Generating neighbors without a deadend check.","Generating neighbors without a visited check.","Adding duplicates to the BFS frontier."],"equivalentVariants":["Use a set for deadends and a set for seen states.","Use any equivalent membership structure that prevents dead or repeated states from being processed."],"proofSnippets":[{"id":"py-open-lock-filter-and-mark-neighbors","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1\n            if state == target:\n                return steps\n            for i in range(4):\n                digit = int(state[i])\n                for move in [-1, 1]:\n                    next_digit = (digit + move) % 10\n                    next_state = state[:i] + str(next_digit) + state[i + 1:]\n                    if next_state not in dead and next_state not in seen:\n                        seen.add(next_state)"}]}},{"id":"expand-neighbors","title":"Complete BFS neighbor expansion","description":"Generate one-turn neighbors and enqueue each valid unseen state with the next distance.","commonMistakes":["Missing backward turns","Forgetting modulo wraparound","Enqueuing deadends"],"hint":"For each of four positions, try -1 and +1, filter by dead and seen, then enqueue the accepted next state.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"distance-neighbors","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Derive and enqueue valid neighboring lock states from the current state.","doneWhen":"The nested neighbor loops generate next states and append unseen valid states to the queue with steps + 1.","shouldFailWhen":"The code does not expand neighbors from the dequeued state.","roles":["current state","neighbor state","queue"],"mustProve":["The solution expands frontier neighbors."],"mustNotAccept":["Adding arbitrary states that are not one wheel turn away."],"proofSnippets":[{"id":"py-open-lock-expand-neighbors","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1\n            if state == target:\n                return steps\n            for i in range(4):\n                digit = int(state[i])\n                for move in [-1, 1]:\n                    next_digit = (digit + move) % 10\n                    next_state = state[:i] + str(next_digit) + state[i + 1:]\n                    if next_state not in dead and next_state not in seen:\n                        seen.add(next_state)\n                        queue.append((next_state, steps + 1))"}]}},{"id":"return-unreachable","title":"Return -1 when BFS exhausts","description":"If the queue empties without finding target, return -1.","commonMistakes":["Returning 0 when no route exists","Falling off the function without an unreachable result"],"hint":"Place return -1 after the while loop, not inside the neighbor loop.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"returns_terminal_bfs_result","scope":"unreachable-return","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Report that target cannot be reached once BFS has no states left to process.","doneWhen":"A direct return -1 runs after the frontier loop finishes.","shouldFailWhen":"The code returns a non-negative value or has no unreachable return after the loop.","roles":["frontier queue","unreachable result"],"mustProve":["An exhausted BFS frontier returns -1."],"mustNotAccept":["Returning -1 before all queued states are processed.","Returning 0 when target was not reached."],"proofSnippets":[{"id":"py-open-lock-return-unreachable","language":"python","code":"class Solution:\n    def openLock(self, deadends: list[str], target: str) -> int:\n        dead = set(deadends)\n        if \"0000\" in dead:\n            return -1\n        queue = [(\"0000\", 0)]\n        seen = set([\"0000\"])\n        head = 0\n        while head < len(queue):\n            state, steps = queue[head]\n            head += 1\n            if state == target:\n                return steps\n            for i in range(4):\n                digit = int(state[i])\n                for move in [-1, 1]:\n                    next_digit = (digit + move) % 10\n                    next_state = state[:i] + str(next_digit) + state[i + 1:]\n                    if next_state not in dead and next_state not in seen:\n                        seen.add(next_state)\n                        queue.append((next_state, steps + 1))\n        return -1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Wrap up","title":"You built it","summary":"Review the route or visualize the final search.","workspacePanel":"code","takeaways":[{"title":"The fewest moves is a shortest-path question","body":"Each lock combination is a node, and each one-wheel turn is one unweighted edge."},{"title":"The first time target is pulled gives the fewest moves","body":"Breadth-first search expands the states ring by ring, in order of how many moves they take to reach."},{"title":"Mark a state seen when it is queued","body":"Each state then enters the queue at most once, which stops duplicates and cycles."},{"title":"Checking target on each pull covers the 0-move case","body":"When target is \"0000\", the first pull returns 0 with no extra branch. The one guard needed is a dead \"0000\", which returns -1 before the search starts."},{"title":"The search is O(10000) in time and space","body":"It visits each of the 10000 combinations at most once."}],"nextAction":"Submit runs your solution against every test case."}],"slidesOrigin":"authored"},"version":1}
