{"id":"shortest-path-in-binary-matrix","title":"Shortest Path in Binary Matrix","difficulty":"medium","patterns":["graph-bfs"],"primaryConcept":"graph-grid-fill","concepts":["graph-grid-fill"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"grid","sizeMetric":"matrix-cells","constraints":["binary-int","square-matrix","eight-direction-grid-path"],"sizes":[1,4,9,25,100]},"description":"Given an `n x n` binary matrix `grid`, return the length of the shortest clear path from the top-left cell to the bottom-right cell. A clear path may move in any of the 8 directions and may only visit cells with value `0`.\n\nIf no such path exists, return `-1`.","examples":[{"input":"grid = [[0,1],[1,0]]","output":"2","explanation":"Move diagonally from the top-left cell to the bottom-right cell."},{"input":"grid = [[0,0,0],[1,1,0],[1,1,0]]","output":"4","explanation":"One shortest path visits (0,0), (0,1), (1,2), and (2,2)."},{"input":"grid = [[1,0],[0,0]]","output":"-1","explanation":"The starting cell is blocked, so no clear path can begin."}],"constraints":[{"id":"n-len-grid","text":"n == len(grid)"},{"id":"n-len-grid-i","text":"n == len(grid[i])"},{"id":"1-n-100","text":"1 <= n <= 100"},{"id":"grid-i-j-is-0-or-1","text":"grid[i][j] is 0 or 1","check":{"kind":"domain","target":"grid","selector":"nestedArrayItems","allowed":[0,1],"rectangular":true}}],"starterCode":"class Solution:\n    def shortestPathBinaryMatrix(self, grid: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"shortestPathBinaryMatrix","testCases":[{"id":"1","input":{"grid":[[0,1],[1,0]]},"expected":2,"description":"Diagonal two-cell path."},{"id":"2","input":{"grid":[[0,0,0],[1,1,0],[1,1,0]]},"expected":4,"description":"Prompt example with a path around blockers."},{"id":"3","input":{"grid":[[1,0],[0,0]]},"expected":-1,"description":"Blocked starting cell."},{"id":"4","input":{"grid":[[0]]},"expected":1,"description":"Single open cell is already the destination."},{"id":"5","input":{"grid":[[0,0],[0,1]]},"expected":-1,"description":"Blocked destination cell."},{"id":"h1","input":{"grid":[[0,1,1],[1,0,1],[1,1,0]]},"expected":3,"description":"Only a diagonal path is open."},{"id":"h2","input":{"grid":[[0,0,0],[0,0,0],[0,0,0]]},"expected":3,"description":"All cells open, so the diagonal path is shortest."},{"id":"h3","input":{"grid":[[0,1,0],[1,1,0],[1,1,0]]},"expected":-1,"description":"The start cell has no open neighbor."},{"id":"h4","input":{"grid":[[0,0,0,1],[1,1,0,1],[1,1,0,0],[1,1,1,0]]},"expected":5,"description":"A winding clear route is longer than the diagonally open cases."},{"id":"h5","input":{"grid":[[0,1,0],[1,1,1],[0,1,0]]},"expected":-1,"description":"A wall of blocked cells prevents any valid path."},{"id":"topup-blocked-start","input":{"grid":[[0,1,0],[1,0,1],[0,1,0]]},"expected":3,"description":"A blocked start cell has no valid path."},{"id":"topup-winding-open-path","input":{"grid":[[0,1,0,0],[0,0,1,0],[1,0,0,0],[1,1,1,0]]},"expected":4,"description":"A larger grid requires diagonal movement around blockers."}],"hints":[{"level":1,"content":"A shortest unweighted path is a breadth-first search problem.","revealPattern":false},{"level":2,"content":"Store each frontier item as row, column, and distance from the start.","revealPattern":true},{"level":3,"content":"Mark a cell visited when it is enqueued so it is never processed twice.","revealPattern":true}],"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":"bfs-frontier","name":"BFS with visited grid","summary":"Reject blocked endpoints, then expand a queue of open cells with their path length.","decisionReason":"Expanding ring by ring reaches every cell at its fewest-cells length in O(n^2), so the corner's first arrival off the queue is already its shortest path.","complexity":{"time":"O(n^2)","space":"O(n^2)"},"tradeoffs":["Runs in O(n^2) time and uses O(n^2) space."],"isOptimal":true},{"id":"dfs-all-paths","name":"Explore all paths with DFS","summary":"Try every possible clear path and keep the shortest.","decisionReason":"It explores a whole branch before backing up, so the first path it finds is not the shortest, and enumerating every clear path from corner to corner is exponential.","complexity":{"time":"Exponential","space":"O(n^2)"},"tradeoffs":["Runs in Exponential time and uses O(n^2) space."],"isOptimal":false},{"id":"greedy-diagonal","name":"Always move diagonally when possible","summary":"Choose locally promising moves toward the destination.","decisionReason":"Always stepping toward the corner walks into a blocked pocket, like a 1 sitting on the diagonal, and misses the shorter route around it, so it can report a non-shortest length or no path at all.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["Runs in O(n) time and uses O(1) space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"check-blocked-endpoints","title":"Reject a blocked start or target","description":"Return -1 right away when the top-left or bottom-right cell is blocked.","commonMistakes":["Seeding the search from a blocked start cell","Forgetting that a blocked destination can never be reached"],"hint":"If the top-left or bottom-right cell holds 1, no clear path exists, so return -1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"short_circuits_trivial_case","scope":"check-no-fresh","readMode":"bfs-queue-value-query-v1","expected":{"unreachableSentinel":-1}}]},"semanticSpec":{"intent":"Short-circuit the impossible case where either endpoint is blocked before any search begins.","doneWhen":"This step is done when the code returns -1 as soon as the start or destination cell is blocked.","shouldFailWhen":"This step should fail if the search still runs on a blocked endpoint, or if the blocked case returns anything other than -1.","roles":["start cell","destination cell","early return"],"mustProve":["The start and destination cells are inspected before the frontier is seeded.","A blocked endpoint returns -1 immediately."],"mustNotAccept":["Entering the search loop when an endpoint is blocked.","Returning a distance for a grid whose start or destination is blocked."],"equivalentVariants":["Guard both endpoints up front and exit with -1 when either is blocked.","Use any equivalent pre-search check that rejects a blocked start or destination."],"proofSnippets":[{"id":"py-spbm-reject-blocked-endpoints","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1"}]}},{"id":"init-frontier","title":"Seed the frontier with the start","description":"Put the start cell in the queue with path length 1 and mark it visited.","commonMistakes":["Forgetting to carry the path length with each queued cell","Marking the start visited only after it is dequeued"],"hint":"Queue the start cell together with the length 1, and record the start as visited at the same moment.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"initializes_frontier_and_aux_state","scope":"init-queue","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Seed the breadth-first frontier with the start cell and its path length, and record it as visited.","doneWhen":"This step is done when the queue holds the start cell with length 1 and the visited record marks the start.","shouldFailWhen":"This step should fail if the structure is not FIFO, if the length is not stored with the cell, or if the start is left unvisited at seeding time.","roles":["frontier queue","start cell","visited record"],"mustProve":["The queue is seeded with the start cell and its starting path length.","The start cell is marked visited as it is enqueued."],"mustNotAccept":["Using a stack or recursion instead of a FIFO queue.","Enqueuing the start without its length, or marking it visited only on dequeue."],"equivalentVariants":["Seed a FIFO frontier with the start coordinate and length 1, marking it visited together.","Use any equivalent queue payload that carries the cell and its path length."],"proofSnippets":[{"id":"py-spbm-init-frontier","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True"}]}},{"id":"bfs-loop","title":"Drain the frontier in order","description":"Loop while the queue is not empty, taking the next cell from the front each time.","commonMistakes":["Taking from the back, which turns the search depth-first","Scanning the whole grid again instead of advancing the frontier"],"hint":"Each pass removes one cell from the front of the queue.","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":"Drive the search level by level with a FIFO queue until the frontier is empty.","doneWhen":"This step is done when the loop repeatedly removes the front cell until the queue is empty, preserving first-in first-out order.","shouldFailWhen":"This step should fail if the traversal pops from the back, behaves like a stack or recursion, or loses the path length carried with each cell.","roles":["FIFO queue","current cell","carried path length"],"mustProve":["The loop consumes the frontier in first-in first-out order.","Each removed entry carries a cell and its path length."],"mustNotAccept":["Using last-in first-out (stack) order for the search loop.","Processing cells without the carried path length."],"equivalentVariants":["Loop until the frontier is empty, always taking the oldest cell first.","Use any equivalent breadth-first traversal that preserves arrival order."],"proofSnippets":[{"id":"py-spbm-bfs-loop","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True\n    while queue:\n        r, c, dist = queue.popleft()"}]}},{"id":"expand-neighbors","title":"Look at all eight neighbors","description":"For each cell, try every move and keep only in-bounds, unvisited, open neighbors.","commonMistakes":["Considering only the four orthogonal moves","Forgetting that a neighbor must hold 0 to be walkable"],"hint":"The move list has all eight neighbors, including the four diagonals.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"check-neighbors","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Inspect all eight neighbors of each cell so diagonal moves are allowed.","doneWhen":"This step is done when each cell considers its eight neighbors, with bounds, visited, and open checks before stepping in.","shouldFailWhen":"This step should fail if only four directions are considered, if a neighbor is read out of bounds, or if blocked cells are treated as walkable.","roles":["current cell","eight move offsets","neighbor coordinates"],"mustProve":["The code iterates over all eight neighbor offsets.","Each candidate is bounds-checked and required to be open before it is used."],"mustNotAccept":["Restricting movement to four orthogonal neighbors.","Stepping onto a blocked cell or reading outside the grid."],"equivalentVariants":["Inspect all eight neighbors with bounds, visited, and open checks.","Use either an offset list or explicit branches as long as all eight moves are covered."],"proofSnippets":[{"id":"py-spbm-expand-neighbors","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True\n    directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n    while queue:\n        r, c, dist = queue.popleft()\n        for dr, dc in directions:\n            nr = r + dr\n            nc = c + dc\n            if 0 <= nr < n and 0 <= nc < n and not visited[nr][nc] and grid[nr][nc] == 0:\n                pass"}]}},{"id":"enqueue-open-cells","title":"Record and queue each open neighbor","description":"Mark every valid neighbor visited and queue it with the next path length.","commonMistakes":["Queuing the current cell instead of the neighbor","Marking the neighbor visited only when it is later removed"],"hint":"Mark the neighbor visited as it is queued, and store its path length as one more than the current cell.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"enqueues_derived_frontier_state","scope":"rot-fresh"}]},"semanticSpec":{"intent":"Mark each valid neighbor visited and enqueue it with a path length one greater than the current cell.","doneWhen":"This step is done when each open neighbor is marked visited and queued with the incremented path length.","shouldFailWhen":"This step should fail if the neighbor is queued without being marked visited, if the original cell is queued instead, or if the path length is not increased.","roles":["valid neighbor","visited record","next path length"],"mustProve":["Each valid neighbor is marked visited at the moment it is queued.","The queued entry stores the path length increased by one."],"mustNotAccept":["Queuing a neighbor while leaving it unvisited.","Reusing the current path length instead of adding one."],"equivalentVariants":["Mark a neighbor visited and queue it with the current length plus one.","Use any equivalent record-then-enqueue step that increments the path length."],"proofSnippets":[{"id":"py-spbm-enqueue-open-cells","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True\n    directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n    while queue:\n        r, c, dist = queue.popleft()\n        for dr, dc in directions:\n            nr = r + dr\n            nc = c + dc\n            if 0 <= nr < n and 0 <= nc < n and not visited[nr][nc] and grid[nr][nc] == 0:\n                visited[nr][nc] = True\n                queue.append((nr, nc, dist + 1))"}]}},{"id":"return-distance","title":"Return the moment you reach the corner","description":"When a removed cell is the bottom-right corner, return its path length.","commonMistakes":["Counting moves between cells instead of the cells on the path","Draining the whole queue before returning even after the corner is reached"],"hint":"The first time the bottom-right cell is removed from the queue, its stored length is the answer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"returns_terminal_result_during_frontier_expansion","scope":"return-result","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Return the path length the first time the destination cell is removed from the frontier, and -1 if it is never reached.","doneWhen":"This step is done when the destination, on removal, returns its carried path length, while an emptied queue returns -1.","shouldFailWhen":"This step should fail if the return ignores the carried length, keeps searching after the destination is reached, or never reports the unreachable case.","roles":["destination cell","carried path length","returned answer"],"mustProve":["The destination returns its carried path length the first time it is removed.","A frontier that empties without reaching the destination returns -1."],"mustNotAccept":["Returning a move count that is one less than the cells on the path.","Continuing to expand the frontier after the destination is removed."],"equivalentVariants":["Return the stored length on the first removal of the destination, otherwise -1.","Use any equivalent terminal check that maps reaching the corner to its length and the empty frontier to -1."],"proofSnippets":[{"id":"py-spbm-return-distance","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True\n    directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n    while queue:\n        r, c, dist = queue.popleft()\n        if r == n - 1 and c == n - 1:\n            return dist\n        for dr, dc in directions:\n            nr = r + dr\n            nc = c + dc\n            if 0 <= nr < n and 0 <= nc < n and not visited[nr][nc] and grid[nr][nc] == 0:\n                visited[nr][nc] = True\n                queue.append((nr, nc, dist + 1))\n    return -1"}]}}],"complexityAnalysis":{"time":{"complexity":"O(n^2)","explanation":"Each grid cell can be enqueued and processed at most once."},"space":{"complexity":"O(n^2)","explanation":"The visited grid and queue can each hold up to all cells."}},"slides":[{"id":"read-the-grid","chapter":"The grid","kind":"info","eyebrow":"Read the problem","title":"The fewest cells from corner to corner","workspacePanel":"problem","body":["You get an n by n grid where 0 is open and 1 is blocked. Return the length of the shortest open path from the top-left cell to the bottom-right, moving straight or diagonally to any surrounding cell and counting every cell on the path. Return -1 when no such path exists.","Paths branch through eight directions and can revisit the same open cell. Expanding by distance makes the first arrival at the bottom-right cell the shortest."]},{"id":"one-path-not-shortest","chapter":"The idea","kind":"info","eyebrow":"See the shape","title":"Finding a path is easy, finding the shortest is the work","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"wander","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":2,"c":2,"filled":[[0,0],[1,0],[2,0],[2,1],[2,2]],"changed":[]}}]},"body":["Walking outward and following open cells until you stumble onto the corner does find a route. The trouble is the first route you find is rarely the shortest one.","Here a wandering walk reaches the corner along five cells, down the left edge and across the bottom. A route that cuts through the middle is plainly shorter, but the same grid hides paths of very different lengths.","So the real question is how to explore the grid in an order that hands you the shortest path first, before any longer one."]},{"id":"first-arrival","chapter":"The idea","kind":"case-probe","eyebrow":"Find the order","title":"What exploration order makes the first arrival at a cell its shortest path?","summary":"A wandering walk found the corner at length 5, yet a shorter route through the middle was sitting right there.","workspacePanel":"visualizer","options":[{"id":"by-distance","label":"Expand every cell one step away, then every cell two steps away, and so on","rationale":"Reaching all cells at length d before any cell at length d + 1 means the first time you touch a cell is along the fewest cells. The first time you touch the corner is its shortest path.","isCorrect":true},{"id":"follow-one","label":"Follow one path as far as it goes, then back up and try another","rationale":"Diving down a single path can reach the corner the long way first, the way the five-cell walk did. The first arrival is then not the shortest.","isCorrect":false},{"id":"toward-goal","label":"Always step toward the corner, choosing the cell that looks closest","rationale":"Greedily heading for the corner can walk into a blocked pocket and miss a shorter route around it, so first arrival carries no shortest guarantee.","isCorrect":false}],"answer":"Expand cells in rings of equal length: all length-d cells before any length-(d+1) cell. The first time a ring touches the corner is the shortest path.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rings","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":0,"c":0,"filled":[[0,0]],"frontier":[[0,1],[1,0],[1,1]],"changed":[]}}]}},{"id":"diagonal-shortcut","chapter":"The idea","kind":"case-probe","eyebrow":"Count the moves","title":"On the all-open 3 by 3 grid, how long is the shortest corner-to-corner path?","summary":"A move may land on any of the eight surrounding cells, diagonals included.","workspacePanel":"visualizer","options":[{"id":"three","label":"3, stepping diagonally through the center","rationale":"(0,0) to (1,1) to (2,2) is three cells. Each diagonal step crosses a row and a column at once, so the diagonal is the shortest route across an open grid.","isCorrect":true},{"id":"five","label":"5, moving only up, down, left, and right","rationale":"Five is the shortest path if diagonals are banned: two rights and two downs land on five cells. But diagonal moves are allowed here, and they cut it to three.","isCorrect":false},{"id":"four","label":"4, one move per edge of the grid","rationale":"The length is the number of cells stood on, not edges crossed. Three cells on the diagonal give length 3, not 4.","isCorrect":false}],"answer":"3. Diagonal moves cross a row and a column together, so the open grid is shortest along its diagonal. Banning diagonals would force length 5 instead.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"diagonal","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":2,"c":2,"filled":[[0,0],[1,1],[2,2]],"changed":[]}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which search should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":0,"c":0,"filled":[[0,0]],"frontier":[[0,1],[1,0],[1,1]],"changed":[]}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Seed the start, expand ring by ring","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":0,"c":0,"filled":[[0,0]],"changed":[]}}]},"body":["The queue starts with the open top-left cell at path length 1, and that cell is marked visited. Every other cell is still untouched.","Each round removes a cell, looks at its eight neighbors, and queues each open, unvisited one at one more than the current length, marking it visited as it goes.","The first time the bottom-right cell comes off the queue, its length is the answer. We trace the all-open 3 by 3 grid, expecting 3."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the search","title":"Trace the spreading frontier","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ring-one","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":0,"c":0,"filled":[[0,0],[0,1],[1,0],[1,1]],"changed":[[0,1],[1,0],[1,1]],"frontier":[[0,1],[1,0],[1,1]]}},{"id":"reach-center","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[1,0],[1,1],[0,2],[1,2],[2,0],[2,1],[2,2]],"changed":[[2,2]],"frontier":[[0,2],[1,2],[2,0],[2,1],[2,2]]}},{"id":"reach-corner","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":2,"c":2,"filled":[[0,0],[0,1],[1,0],[1,1],[0,2],[1,2],[2,0],[2,1],[2,2]],"changed":[],"frontier":[]}}]},"beats":[{"id":"ring-one","title":"The start expands. Which length do (0,1), (1,0), and (1,1) get?","summary":"The queue held only the start at length 1.","prompt":"The start at length 1 queues its open neighbors.","options":[{"id":"two","label":"2","rationale":"Each is one step from the start, so its length is 1 + 1 = 2. The diagonal neighbor (1,1) reaches the center at length 2, the same as the straight neighbors.","isCorrect":true},{"id":"mixed","label":"1 for the straight neighbors, 2 for the diagonal one","rationale":"A diagonal move counts the same as a straight one here, one step. All three neighbors land at length 2.","isCorrect":false},{"id":"one","label":"1, the same as the start","rationale":"Length 1 is the start cell alone. A neighbor stands on a second cell, so its length is 2.","isCorrect":false}],"answer":"All three reach length 2, including the diagonal center cell (1,1)."},{"id":"reach-center","title":"After the center at (1,1) expands, what length does the corner (2,2) get?","summary":"The center (1,1) was reached at length 2 and is now removed.","prompt":"The corner (2,2) is the diagonal neighbor of the center.","options":[{"id":"three","label":"3","rationale":"The corner is one diagonal step from the center, so its length is 2 + 1 = 3. It is queued at 3 and marked visited now.","isCorrect":true},{"id":"four","label":"4","rationale":"Four would mean an extra cell on the way. The center sits diagonally adjacent to the corner, one step, giving length 3.","isCorrect":false},{"id":"two","label":"2, the same ring as the center","rationale":"The corner is one step past the center, so it belongs to the next ring at length 3.","isCorrect":false}],"answer":"The corner is queued at length 3, one diagonal step past the center."},{"id":"reach-corner","title":"The corner (2,2) comes off the queue. What is returned?","summary":"The corner was recorded at length 3.","prompt":"The search removes the bottom-right cell.","options":[{"id":"ret-three","label":"3","rationale":"The first removal of the corner carries length 3, and the first arrival is the shortest, so the search returns 3.","isCorrect":true},{"id":"ret-five","label":"5","rationale":"Five is the corner length without diagonal moves. Diagonals are allowed, so the corner was reached at length 3.","isCorrect":false},{"id":"keep-going","label":"Nothing yet, keep draining the queue first","rationale":"There is no need to drain the rest. The first time the corner is removed its length is already minimal, so the search returns immediately.","isCorrect":false}],"answer":"3. The first removal of the corner carries the shortest length, so the search returns 3 at once."}]},{"id":"visited-on-pop-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could you mark a cell visited only when you remove it?","summary":"Marking each cell visited as it comes off the queue passes the small grids and still returns the right length, since the first removal of any cell is already its shortest. But while a cell waits in the queue, nothing has marked it yet. Watch what its neighbors do with it.","workspacePanel":"trace","pitfall":"The code below marks a cell visited only when it is removed from the queue, not when it is added.","whyItMatters":"While a cell waits in the queue it is unmarked, so every neighbor that reaches it queues it again. The frontier fills with duplicates and each cell is processed several times, which balloons the work on a large grid. Mark a cell visited the moment you queue it, so it is never added twice.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def shortestPathBinaryMatrix(grid: list[list[int]]) -> int:\n    from collections import deque\n    rows = len(grid)\n    cols = len(grid[0])\n    visited: list[list[bool]] = [[False] * cols for _ in range(rows)]\n    def neighbors(r: int, c: int) -> list[list[int]]:\n        result: list[list[int]] = []\n        for dr, dc in [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]:\n            nr = r + dr\n            nc = c + dc\n            if 0 <= nr < rows and 0 <= nc < cols:\n                result.append([nr, nc])\n        return result\n    queue = deque([[0, 0, 1]])\n    while queue:\n        r, c, dist = queue.popleft()\n        if r == rows - 1 and c == cols - 1:\n            return dist\n        visited[r][c] = True\n        for nr, nc in neighbors(r, c):\n            if not visited[nr][nc] and grid[nr][nc] == 0:\n                queue.append([nr, nc, dist + 1])\n    return -1","steps":[{"id":"seed-start","title":"The start queues its three open neighbors","codeLine":22,"summary":"On the all-open 2 by 2 grid, popping the start at (0,0) queues (0,1), (1,0), and the corner (1,1), each at length 2.","state":{"grid":[[0,0],[0,0]],"r":0,"c":0,"filled":[[0,0]],"frontier":[[0,1],[1,0],[1,1]],"changed":[[0,0]]}},{"id":"requeue-corner","title":"Marking on removal re-queues cells already waiting","codeLine":19,"summary":"Popping (0,1) marks it now, but its neighbors (1,0) and (1,1) are still unmarked while they wait in the queue, so both get queued a second time. The frontier now holds each of them twice.","state":{"grid":[[0,0],[0,0]],"r":0,"c":1,"filled":[[0,0],[0,1]],"frontier":[[1,0],[1,1],[1,0],[1,1]],"changed":[[0,1]]}},{"id":"reprocessed","title":"The stale duplicates are processed again","codeLine":16,"summary":"The first copies of (1,0) and (1,1) come off and mark them, but their duplicates still sit in the queue. Each is removed and reprocessed a second time, wasted work that only grows as the grid gets bigger.","state":{"grid":[[0,0],[0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[1,0],[1,1]],"frontier":[[1,0],[1,1]],"changed":[[1,1]]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const rows = grid.length;\nconst cols = grid[0].length;\nconst visited = Array.from({ length: rows }, () => Array(cols).fill(false));\nfunction neighbors(r, c) {\n    const result = [];\n    for (const [dr, dc] of [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]) {\n        const nr = r + dr;\n        const nc = c + dc;\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            result.push([nr, nc]);\n        }\n    }\n    return result;\n}\nconst queue = new Deque([[0, 0, 1]]);\nwhile (queue.size() > 0) {\n    const [r, c, dist] = queue.popFront();\n    if (r === (rows - 1) && c === (cols - 1)) {\n        return dist;\n    }\n    visited[r][c] = true;\n    for (const [nr, nc] of neighbors(r, c)) {\n        if (!visited[nr][nc] && grid[nr][nc] === 0) {\n            queue.pushBack([nr, nc, (dist + 1)]);\n        }\n    }\n}\nreturn -1;","lineMap":{"3":1,"4":2,"5":3,"7":5,"8":6,"9":7,"10":8,"11":9,"12":10,"13":13,"14":15,"15":16,"16":17,"17":18,"18":19,"19":21,"20":22,"21":23,"22":24,"23":28},"statementBundles":{"5":{"startLine":3,"endLine":4},"12":{"startLine":10,"endLine":12},"13":{"startLine":13,"endLine":14},"18":{"startLine":19,"endLine":20},"22":{"startLine":24,"endLine":27}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const rows = grid.length;\nconst cols = grid[0].length;\nconst visited = Array.from({ length: rows }, () => Array(cols).fill(false));\nfunction neighbors(r: number, c: number): Array<Array<number>> {\n    const result: Array<Array<number>> = [];\n    for (const [dr, dc] of [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]) {\n        const nr = r + dr;\n        const nc = c + dc;\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            result.push([nr, nc]);\n        }\n    }\n    return result;\n}\nconst queue: Deque<Array<number>> = new Deque([[0, 0, 1]]);\nwhile (queue.size() > 0) {\n    const [r, c, dist] = queue.popFront()!;\n    if (r === (rows - 1) && c === (cols - 1)) {\n        return dist;\n    }\n    visited[r][c] = true;\n    for (const [nr, nc] of neighbors(r, c)) {\n        if (!visited[nr][nc] && grid[nr][nc] === 0) {\n            queue.pushBack([nr, nc, (dist + 1)]);\n        }\n    }\n}\nreturn -1;","lineMap":{"3":1,"4":2,"5":3,"7":5,"8":6,"9":7,"10":8,"11":9,"12":10,"13":13,"14":15,"15":16,"16":17,"17":18,"18":19,"19":21,"20":22,"21":23,"22":24,"23":28},"statementBundles":{"5":{"startLine":3,"endLine":4},"12":{"startLine":10,"endLine":12},"13":{"startLine":13,"endLine":14},"18":{"startLine":19,"endLine":20},"22":{"startLine":24,"endLine":27}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static List<List<Integer>> neighbors(int r, int c, int rows, int cols) {\n    List<List<Integer>> result = new ArrayList<>();\n    for (List<Integer> item : new ArrayList<>(Arrays.asList(new ArrayList<>(List.of(-1, -1)), new ArrayList<>(List.of(-1, 0)), new ArrayList<>(List.of(-1, 1)), new ArrayList<>(List.of(0, -1)), new ArrayList<>(List.of(0, 1)), new ArrayList<>(List.of(1, -1)), new ArrayList<>(List.of(1, 0)), new ArrayList<>(List.of(1, 1))))) {\n        int dr = item.get(0);\n        int dc = item.get(1);\n        int nr = r + dr;\n        int nc = c + dc;\n        if (((0 <= nr && nr < rows) && (0 <= nc && nc < cols))) {\n            result.add(new ArrayList<>(List.of(nr, nc)));\n        }\n    }\n    return result;\n}\n\nint rows = grid.size();\nint cols = grid.get(0).size();\nList<List<Boolean>> visited = new ArrayList<>();\nfor (int i = 0; i < rows; i++) {\n    List<Boolean> items0 = new ArrayList<>();\n    for (int index = 0; index < cols; index++) {\n        items0.add(false);\n    }\n    visited.add(items0);\n}\nDeque<List<Integer>> queue = new ArrayDeque<>(List.of(new ArrayList<>(List.of(0, 0, 1))));\nwhile (!queue.isEmpty()) {\n    List<Integer> item = queue.pollFirst();\n    int r = item.get(0);\n    int c = item.get(1);\n    int dist = item.get(2);\n    if ((r == (rows - 1) && c == (cols - 1))) {\n        return dist;\n    }\n    visited.get(r).set(c, true);\n    for (List<Integer> itemEntry : neighbors(r, c, rows, cols)) {\n        int nr = itemEntry.get(0);\n        int nc = itemEntry.get(1);\n        if ((!visited.get(nr).get(nc) && grid.get(nr).get(nc) == 0)) {\n            queue.addLast(new ArrayList<>(List.of(nr, nc, (dist + 1))));\n        }\n    }\n}\nreturn -1;","lineMap":{"3":15,"4":16,"5":17,"7":2,"8":3,"9":6,"10":7,"11":8,"12":9,"13":12,"14":25,"15":26,"16":27,"17":31,"18":32,"19":34,"20":35,"21":38,"22":39,"23":43},"statementBundles":{"5":{"startLine":17,"endLine":24},"8":{"startLine":3,"endLine":5},"12":{"startLine":9,"endLine":11},"13":{"startLine":12,"endLine":13},"16":{"startLine":27,"endLine":30},"18":{"startLine":32,"endLine":33},"20":{"startLine":35,"endLine":37},"22":{"startLine":39,"endLine":42}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int rows = grid.Count;\nint cols = grid[0].Count;\nList<List<bool>> visited = Enumerable.Range(0, rows).Select(_ => Enumerable.Repeat<bool>(false, cols).ToList()).ToList();\nList<List<int>> Neighbors(int r, int c) {\n    List<List<int>> result = new();\n    foreach (var item in new List<List<int>> { new List<int> { -1, -1 }, new List<int> { -1, 0 }, new List<int> { -1, 1 }, new List<int> { 0, -1 }, new List<int> { 0, 1 }, new List<int> { 1, -1 }, new List<int> { 1, 0 }, new List<int> { 1, 1 } }) {\n        int dr = item[0];\n        int dc = item[1];\n        int nr1 = r + dr;\n        int nc1 = c + dc;\n        if (0 <= nr1 && nr1 < rows && 0 <= nc1 && nc1 < cols) {\n            result.Add(new List<int> { nr1, nc1 });\n        }\n    }\n    return result;\n    return null;\n}\nQueue<List<int>> queue = new(new[] { new List<int> { 0, 0, 1 } });\nwhile (queue.Count > 0) {\n    List<int> item = queue.Dequeue();\n    int r = item[0];\n    int c = item[1];\n    int dist = item[2];\n    if (r == rows - 1 && c == cols - 1) {\n        return dist;\n    }\n    visited[r][c] = true;\n    foreach (var item1 in Neighbors(r, c)) {\n        int nr = item1[0];\n        int nc = item1[1];\n        if (!visited[nr][nc] && grid[nr][nc] == 0) {\n            queue.Enqueue(new List<int> { nr, nc, dist + 1 });\n        }\n    }\n}\nreturn -1;","lineMap":{"3":1,"4":2,"5":3,"7":5,"8":6,"9":9,"10":10,"11":11,"12":12,"13":15,"14":18,"15":19,"16":20,"17":24,"18":25,"19":27,"20":28,"21":31,"22":32,"23":36},"statementBundles":{"5":{"startLine":3,"endLine":4},"8":{"startLine":6,"endLine":8},"12":{"startLine":12,"endLine":14},"13":{"startLine":15,"endLine":17},"16":{"startLine":20,"endLine":23},"18":{"startLine":25,"endLine":26},"20":{"startLine":28,"endLine":30},"22":{"startLine":32,"endLine":35}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int rows = grid.size();\nint cols = grid[0].size();\nvector<vector<bool>> visited = vector<vector<bool>>(rows, vector<bool>(cols, false));\nauto neighbors = [&]( int r, int c ) -> vector<vector<int>> {\n    vector<vector<int>> result;\n    for (vector<int> item : vector<vector<int>>{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}) {\n        int dr = item[0];\n        int dc = item[1];\n        int nr = r + dr;\n        int nc = c + dc;\n        if (((0 <= nr && nr < rows) && (0 <= nc && nc < cols))) {\n            result.push_back(vector<int>{nr, nc});\n        }\n    }\n    return result;\n};\nvector<vector<int>> queue{{0, 0, 1}};\nwhile (!queue.empty()) {\n    auto popped_item = queue.front(); queue.erase(queue.begin());\n    int r = popped_item[0];\n    int c = popped_item[1];\n    int dist = popped_item[2];\n    if ((r == (rows - 1) && c == (cols - 1))) {\n        return dist;\n    }\n    visited[r][c] = true;\n    for (vector<int> item : neighbors(r, c)) {\n        int nr = item[0];\n        int nc = item[1];\n        if ((!visited[nr][nc] && grid[nr][nc] == 0)) {\n            queue.push_back(vector<int>{nr, nc, (dist + 1)});\n        }\n    }\n}\nreturn -1;","lineMap":{"3":1,"4":2,"5":3,"7":5,"8":6,"9":9,"10":10,"11":11,"12":12,"13":15,"14":17,"15":18,"16":19,"17":23,"18":24,"19":26,"20":27,"21":30,"22":31,"23":35},"statementBundles":{"5":{"startLine":3,"endLine":4},"8":{"startLine":6,"endLine":8},"12":{"startLine":12,"endLine":14},"13":{"startLine":15,"endLine":16},"16":{"startLine":19,"endLine":22},"18":{"startLine":24,"endLine":25},"20":{"startLine":27,"endLine":29},"22":{"startLine":31,"endLine":34}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"grid":[[0,1,0],[1,1,0],[1,1,0]],"r":0,"c":0,"filled":[[0,0]],"changed":[]}}]},"body":["The ring-by-ring search drained the open 3 by 3 grid and returned 3 the moment the corner came off the queue.","Three small grids deserve a look before you code: one where the start itself is blocked, one that is a single open cell, and one where open cells exist but none of them connect to the corner."]},{"id":"blocked-start-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What is returned when the top-left cell is blocked?","summary":"The grid [[1,0],[0,0]] has value 1 in the top-left cell.","workspacePanel":"visualizer","options":[{"id":"neg-one","label":"-1, no path can begin","rationale":"The path must start at the top-left cell, and a blocked cell cannot be stood on. With no legal start, no clear path exists, so the answer is -1.","isCorrect":true},{"id":"two","label":"2, going around the block","rationale":"There is no other entrance. The path is required to begin at the top-left cell, which is blocked, so nothing can start.","isCorrect":false},{"id":"one","label":"1, the start counts anyway","rationale":"A blocked cell cannot be the first cell of a path. The start being 1 means there is no valid path at all, which is -1.","isCorrect":false}],"answer":"-1. The path must begin at the top-left cell, and a blocked start leaves no clear path to take.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"blocked-start-state","state":{"grid":[[1,0],[0,0]],"r":0,"c":0}}]}},{"id":"single-cell-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What is returned for grid = [[0]]?","summary":"n = 1 and grid[0][0] = 0.","workspacePanel":"visualizer","options":[{"id":"one","label":"1, the starting square counts","rationale":"Length counts the cells stood on. Standing on the single open cell is a path of one cell, and that cell is already the destination, so the answer is 1.","isCorrect":true},{"id":"zero","label":"0, no moves are needed","rationale":"Length is the number of cells on the path, not moves made. One cell stood on is length 1, even with zero moves.","isCorrect":false},{"id":"neg-one","label":"-1, there is nowhere to go","rationale":"The start is open and is already the destination, so a valid path exists. Its length is 1, not -1.","isCorrect":false}],"answer":"1. The lone open cell is both start and destination, and standing on it is a path of one cell.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-cell-state","state":{"grid":[[0]],"r":0,"c":0,"filled":[[0,0]],"changed":[]}}]}},{"id":"walled-off-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What is returned when no open path reaches the corner?","summary":"In [[0,1,0],[1,1,0],[1,1,0]] the start has no open neighbor.","workspacePanel":"visualizer","options":[{"id":"neg-one","label":"-1, the frontier empties without reaching the corner","rationale":"The start has no open neighbor, so the queue drains after the start alone and the corner is never removed. An emptied queue that never reached the corner returns -1.","isCorrect":true},{"id":"three","label":"3, the open cells form a path","rationale":"The open cells in the right column are not connected to the start, which is walled in. The search never reaches them, so there is no path.","isCorrect":false},{"id":"one","label":"1, the start is still counted","rationale":"Reaching only the start is not reaching the destination. The corner is never removed from the queue, so the answer is -1, not 1.","isCorrect":false}],"answer":"-1. The start is walled in, the queue empties without the corner ever coming off it, and that unreachable case returns -1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"walled-off-state","state":{"grid":[[0,1,0],[1,1,0],[1,1,0]],"r":0,"c":0,"filled":[[0,0]],"frontier":[],"changed":[]}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Mark a cell the moment you queue it, and the first time the corner comes off, its length is the answer.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":0,"c":0,"filled":[[0,0]],"changed":[]}}]},"body":["Reject a blocked start or corner first. Then seed the queue with the start at length 1 and mark it visited. Drain the queue from the front, and for each cell scan its eight neighbors, queuing every open, unvisited one at one more length while marking it visited as it is added.","Return the length the first time the corner is removed, and return -1 if the queue empties first."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the shortest-path search","eyebrow":"Code the rule","summary":"Build the BFS: reject blocked endpoints, start from the top-left cell, explore all 8 directions by path length, mark cells when queued, and return the corner's length.","workspacePanel":"code","checkpoints":[{"id":"check-blocked-endpoints","title":"Reject a blocked start or target","description":"Return -1 right away when the top-left or bottom-right cell is blocked.","commonMistakes":["Seeding the search from a blocked start cell","Forgetting that a blocked destination can never be reached"],"hint":"If the top-left or bottom-right cell holds 1, no clear path exists, so return -1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"short_circuits_trivial_case","scope":"check-no-fresh","readMode":"bfs-queue-value-query-v1","expected":{"unreachableSentinel":-1}}]},"semanticSpec":{"intent":"Short-circuit the impossible case where either endpoint is blocked before any search begins.","doneWhen":"This step is done when the code returns -1 as soon as the start or destination cell is blocked.","shouldFailWhen":"This step should fail if the search still runs on a blocked endpoint, or if the blocked case returns anything other than -1.","roles":["start cell","destination cell","early return"],"mustProve":["The start and destination cells are inspected before the frontier is seeded.","A blocked endpoint returns -1 immediately."],"mustNotAccept":["Entering the search loop when an endpoint is blocked.","Returning a distance for a grid whose start or destination is blocked."],"equivalentVariants":["Guard both endpoints up front and exit with -1 when either is blocked.","Use any equivalent pre-search check that rejects a blocked start or destination."],"proofSnippets":[{"id":"py-spbm-reject-blocked-endpoints","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1"}]}},{"id":"init-frontier","title":"Seed the frontier with the start","description":"Put the start cell in the queue with path length 1 and mark it visited.","commonMistakes":["Forgetting to carry the path length with each queued cell","Marking the start visited only after it is dequeued"],"hint":"Queue the start cell together with the length 1, and record the start as visited at the same moment.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"initializes_frontier_and_aux_state","scope":"init-queue","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Seed the breadth-first frontier with the start cell and its path length, and record it as visited.","doneWhen":"This step is done when the queue holds the start cell with length 1 and the visited record marks the start.","shouldFailWhen":"This step should fail if the structure is not FIFO, if the length is not stored with the cell, or if the start is left unvisited at seeding time.","roles":["frontier queue","start cell","visited record"],"mustProve":["The queue is seeded with the start cell and its starting path length.","The start cell is marked visited as it is enqueued."],"mustNotAccept":["Using a stack or recursion instead of a FIFO queue.","Enqueuing the start without its length, or marking it visited only on dequeue."],"equivalentVariants":["Seed a FIFO frontier with the start coordinate and length 1, marking it visited together.","Use any equivalent queue payload that carries the cell and its path length."],"proofSnippets":[{"id":"py-spbm-init-frontier","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True"}]}},{"id":"bfs-loop","title":"Drain the frontier in order","description":"Loop while the queue is not empty, taking the next cell from the front each time.","commonMistakes":["Taking from the back, which turns the search depth-first","Scanning the whole grid again instead of advancing the frontier"],"hint":"Each pass removes one cell from the front of the queue.","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":"Drive the search level by level with a FIFO queue until the frontier is empty.","doneWhen":"This step is done when the loop repeatedly removes the front cell until the queue is empty, preserving first-in first-out order.","shouldFailWhen":"This step should fail if the traversal pops from the back, behaves like a stack or recursion, or loses the path length carried with each cell.","roles":["FIFO queue","current cell","carried path length"],"mustProve":["The loop consumes the frontier in first-in first-out order.","Each removed entry carries a cell and its path length."],"mustNotAccept":["Using last-in first-out (stack) order for the search loop.","Processing cells without the carried path length."],"equivalentVariants":["Loop until the frontier is empty, always taking the oldest cell first.","Use any equivalent breadth-first traversal that preserves arrival order."],"proofSnippets":[{"id":"py-spbm-bfs-loop","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True\n    while queue:\n        r, c, dist = queue.popleft()"}]}},{"id":"expand-neighbors","title":"Look at all eight neighbors","description":"For each cell, try every move and keep only in-bounds, unvisited, open neighbors.","commonMistakes":["Considering only the four orthogonal moves","Forgetting that a neighbor must hold 0 to be walkable"],"hint":"The move list has all eight neighbors, including the four diagonals.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"check-neighbors","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Inspect all eight neighbors of each cell so diagonal moves are allowed.","doneWhen":"This step is done when each cell considers its eight neighbors, with bounds, visited, and open checks before stepping in.","shouldFailWhen":"This step should fail if only four directions are considered, if a neighbor is read out of bounds, or if blocked cells are treated as walkable.","roles":["current cell","eight move offsets","neighbor coordinates"],"mustProve":["The code iterates over all eight neighbor offsets.","Each candidate is bounds-checked and required to be open before it is used."],"mustNotAccept":["Restricting movement to four orthogonal neighbors.","Stepping onto a blocked cell or reading outside the grid."],"equivalentVariants":["Inspect all eight neighbors with bounds, visited, and open checks.","Use either an offset list or explicit branches as long as all eight moves are covered."],"proofSnippets":[{"id":"py-spbm-expand-neighbors","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True\n    directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n    while queue:\n        r, c, dist = queue.popleft()\n        for dr, dc in directions:\n            nr = r + dr\n            nc = c + dc\n            if 0 <= nr < n and 0 <= nc < n and not visited[nr][nc] and grid[nr][nc] == 0:\n                pass"}]}},{"id":"enqueue-open-cells","title":"Record and queue each open neighbor","description":"Mark every valid neighbor visited and queue it with the next path length.","commonMistakes":["Queuing the current cell instead of the neighbor","Marking the neighbor visited only when it is later removed"],"hint":"Mark the neighbor visited as it is queued, and store its path length as one more than the current cell.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"enqueues_derived_frontier_state","scope":"rot-fresh"}]},"semanticSpec":{"intent":"Mark each valid neighbor visited and enqueue it with a path length one greater than the current cell.","doneWhen":"This step is done when each open neighbor is marked visited and queued with the incremented path length.","shouldFailWhen":"This step should fail if the neighbor is queued without being marked visited, if the original cell is queued instead, or if the path length is not increased.","roles":["valid neighbor","visited record","next path length"],"mustProve":["Each valid neighbor is marked visited at the moment it is queued.","The queued entry stores the path length increased by one."],"mustNotAccept":["Queuing a neighbor while leaving it unvisited.","Reusing the current path length instead of adding one."],"equivalentVariants":["Mark a neighbor visited and queue it with the current length plus one.","Use any equivalent record-then-enqueue step that increments the path length."],"proofSnippets":[{"id":"py-spbm-enqueue-open-cells","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True\n    directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n    while queue:\n        r, c, dist = queue.popleft()\n        for dr, dc in directions:\n            nr = r + dr\n            nc = c + dc\n            if 0 <= nr < n and 0 <= nc < n and not visited[nr][nc] and grid[nr][nc] == 0:\n                visited[nr][nc] = True\n                queue.append((nr, nc, dist + 1))"}]}},{"id":"return-distance","title":"Return the moment you reach the corner","description":"When a removed cell is the bottom-right corner, return its path length.","commonMistakes":["Counting moves between cells instead of the cells on the path","Draining the whole queue before returning even after the corner is reached"],"hint":"The first time the bottom-right cell is removed from the queue, its stored length is the answer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"returns_terminal_result_during_frontier_expansion","scope":"return-result","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Return the path length the first time the destination cell is removed from the frontier, and -1 if it is never reached.","doneWhen":"This step is done when the destination, on removal, returns its carried path length, while an emptied queue returns -1.","shouldFailWhen":"This step should fail if the return ignores the carried length, keeps searching after the destination is reached, or never reports the unreachable case.","roles":["destination cell","carried path length","returned answer"],"mustProve":["The destination returns its carried path length the first time it is removed.","A frontier that empties without reaching the destination returns -1."],"mustNotAccept":["Returning a move count that is one less than the cells on the path.","Continuing to expand the frontier after the destination is removed."],"equivalentVariants":["Return the stored length on the first removal of the destination, otherwise -1.","Use any equivalent terminal check that maps reaching the corner to its length and the empty frontier to -1."],"proofSnippets":[{"id":"py-spbm-return-distance","language":"python","code":"from collections import deque\n\ndef shortestPathBinaryMatrix(grid):\n    n = len(grid)\n    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:\n        return -1\n    queue = deque([(0, 0, 1)])\n    visited = [[False] * n for _ in range(n)]\n    visited[0][0] = True\n    directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n    while queue:\n        r, c, dist = queue.popleft()\n        if r == n - 1 and c == n - 1:\n            return dist\n        for dr, dc in directions:\n            nr = r + dr\n            nc = c + dc\n            if 0 <= nr < n and 0 <= nc < n and not visited[nr][nc] and grid[nr][nc] == 0:\n                visited[nr][nc] = True\n                queue.append((nr, nc, dist + 1))\n    return -1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"A breadth-first frontier reaches every cell along the fewest cells, so the corner's first arrival is the shortest path.","workspacePanel":"code","body":["Cells are nodes and open moves are edges. Expanding the frontier ring by ring reaches each cell at its shortest length, so the first time the corner is removed, its length is the answer.","Marking a cell as it enters the queue keeps each cell single in the frontier, and an emptied queue that never reached the corner means -1."],"takeaways":[{"title":"First arrival is shortest","body":"Because the frontier grows one length at a time, the first time a cell is reached is along the fewest cells, so the corner can be returned on its first removal."},{"title":"Mark cells when queued","body":"Marking a cell visited as it is queued keeps it out of the frontier a second time; marking it only on removal lets duplicates pile up."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
