{"id":"zero-one-matrix","title":"01 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":"mat","sizeMetric":"matrix-cells","sizes":[4,9,16,25],"constraints":["binary","contains-zero"]},"description":"Given an m by n binary matrix `mat`, return a matrix where each cell stores the distance to the nearest 0.\n\nDistance is measured by moving one step up, down, left, or right.","examples":[{"input":"mat = [[0,0,0],[0,1,0],[0,0,0]]","output":"[[0,0,0],[0,1,0],[0,0,0]]","explanation":"The only 1 is already adjacent to a 0."},{"input":"mat = [[0,0,0],[0,1,0],[1,1,1]]","output":"[[0,0,0],[0,1,0],[1,2,1]]","explanation":"The bottom middle cell is two steps from the nearest 0."}],"constraints":[{"id":"1-m-n-10-4","text":"1 <= m, n <= 10^4"},{"id":"1-m-n-10-4-2","text":"1 <= m * n <= 10^4"},{"id":"mat-i-j-is-0-or-1","text":"mat[i][j] is 0 or 1","check":{"kind":"domain","target":"mat","selector":"nestedArrayItems","allowed":[0,1],"rectangular":true}},{"id":"there-is-at-least-one-0-in-mat","text":"There is at least one 0 in mat"}],"starterCode":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        # Your code here\n        pass","functionName":"updateMatrix","testCases":[{"id":"1","input":{"mat":[[0,0,0],[0,1,0],[0,0,0]]},"expected":[[0,0,0],[0,1,0],[0,0,0]],"description":"Center cell is one step from a zero."},{"id":"2","input":{"mat":[[0,0,0],[0,1,0],[1,1,1]]},"expected":[[0,0,0],[0,1,0],[1,2,1]],"description":"Bottom middle cell is two steps away."},{"id":"3","input":{"mat":[[1,1,1],[1,0,1],[1,1,1]]},"expected":[[2,1,2],[1,0,1],[2,1,2]],"description":"Single zero expands outward in layers."},{"id":"4","input":{"mat":[[0]]},"expected":[[0]],"description":"Single zero cell."},{"id":"5","input":{"mat":[[1,0,1,1]]},"expected":[[1,0,1,2]],"description":"Single row distances spread left and right."},{"id":"h1","input":{"mat":[[0,0],[0,0]]},"expected":[[0,0],[0,0]]},{"id":"h2","input":{"mat":[[1,1,0,1,1]]},"expected":[[2,1,0,1,2]]},{"id":"h3","input":{"mat":[[1],[0],[1],[1]]},"expected":[[1],[0],[1],[2]]},{"id":"h4","input":{"mat":[[0,1],[1,1]]},"expected":[[0,1],[1,2]]},{"id":"h5","input":{"mat":[[1,1,1],[1,0,1],[1,1,0]]},"expected":[[2,1,2],[1,0,1],[2,1,0]]},{"id":"topup-corner-zero-gradient","input":{"mat":[[0,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]},"expected":[[0,1,2,3],[1,2,3,4],[2,3,4,5],[3,4,5,6]],"description":"A single corner zero creates a Manhattan-distance gradient."},{"id":"topup-two-zero-sources","input":{"mat":[[1,1,0],[1,1,1],[0,1,1]]},"expected":[[2,1,0],[1,2,1],[0,1,2]],"description":"Two zero sources meet in the middle of the grid."}],"hints":[{"level":1,"content":"Start from all zero cells at the same time instead of running a search from every 1."},{"level":2,"content":"Multi-source BFS fills cells in increasing distance order."},{"level":3,"content":"Initialize each zero with distance 0, then assign each unvisited neighbor distance current + 1 when it is first enqueued."}],"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":"multi-source-bfs-with-input-reuse","name":"Multi-source BFS reusing the matrix","summary":"Seed every zero, then write distances directly into the matrix while using a visited marker or value convention to identify unclaimed one cells.","decisionReason":"Writing distances into mat returns the same nearest-zero values in O(rows*cols) time. This flow keeps a separate distance matrix so original 1 cells and newly written distances remain unambiguous in the trace.","complexity":{"time":"O(rows * cols)","space":"O(1) extra besides the returned matrix and queue"},"tradeoffs":["Keeps the multi-source BFS invariant.","Can avoid a separate distance matrix only if the input/output matrix can be safely mutated.","Still needs queue space for the frontier, so the benefit is about distance-state storage rather than total memory disappearing."],"isViable":true,"isOptimal":false,"steps":["Use all zero cells as the starting frontier.","Represent unvisited one cells distinctly from assigned distances.","Assign each one cell only on first discovery."]},{"id":"multi-source-bfs","name":"Multi-source BFS","summary":"Seed the queue with every zero and expand into unvisited cells once.","decisionReason":"This is the intended guided approach because a separate distance matrix makes first discovery and visited state explicit.","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Runs in O(m*n) time and uses O(m*n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-frontier","title":"Seed all zero cells","description":"Create the distance matrix, set every zero cell to distance 0, and enqueue those zero cells.","commonMistakes":["Starting from only the first zero","Leaving zero cells marked as unvisited"],"hint":"Every zero is a BFS source with distance 0.","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":"Initialize BFS with every source cell and a distance matrix that tracks visited cells.","doneWhen":"All zero cells are marked with distance 0 and inserted into the frontier before the BFS loop.","shouldFailWhen":"The queue is missing some zero cells, distances are not initialized, or BFS starts from a one cell.","roles":["distance matrix","frontier queue","zero source cells"],"mustProve":["A frontier queue is initialized before traversal.","The matrix is scanned for zero-valued source cells.","Each source is marked with distance 0 and enqueued."],"mustNotAccept":["Enqueuing only one source when multiple zeros exist.","Starting from unvisited one cells."],"equivalentVariants":["Use a list with a head index or a deque as the BFS queue.","Use any distance/visited matrix that marks source cells as distance 0."],"proofSnippets":[{"id":"py-zero-one-matrix-init-frontier","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))"}]}},{"id":"bfs-loop","title":"Process the BFS queue","description":"Process cells from the BFS frontier in FIFO order so first discovery remains final.","commonMistakes":["Using a stack-like traversal","Looping over the grid repeatedly instead of advancing the frontier","Overwriting distances for cells that were already discovered"],"hint":"The queue discipline matters because a cell should be assigned once, when the nearest frontier reaches it first.","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 traversal from the frontier until every reachable cell has been processed, preserving FIFO first-discovery semantics.","doneWhen":"The code loops while queued cells remain, obtains the next queued cell in FIFO order, and never treats an already-discovered cell as a fresh frontier item.","shouldFailWhen":"The queue is never consumed, traversal uses LIFO behavior, or already-assigned cells can be reprocessed as newly discovered cells.","roles":["frontier queue","FIFO order","current cell","first discovery"],"mustProve":["The loop condition depends on frontier availability.","Each iteration obtains one queued cell in FIFO order.","Already-discovered cells are not converted back into fresh frontier entries."],"mustNotAccept":["A full matrix scan in place of a queue-driven traversal.","Popping from the end as the primary traversal step."],"equivalentVariants":["Use `while head < len(queue)` with a head index.","Use `while queue` with `popleft()` from a deque."],"proofSnippets":[{"id":"py-zero-one-matrix-bfs-loop","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))\n\n        head = 0\n        while head < len(queue):\n            row, col = queue[head]\n            head += 1"}]}},{"id":"expand-neighbors","title":"Check four neighboring cells","description":"For each dequeued cell, generate the four orthogonal neighbors and keep only in-bounds unvisited cells.","commonMistakes":["Using diagonal moves","Forgetting to check bounds","Revisiting cells whose distance is already known"],"hint":"Only unvisited cells with dist == -1 should receive a new distance.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"check-neighbors","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Derive valid neighbor coordinates from each current cell during BFS expansion.","doneWhen":"The code iterates over orthogonal offsets, computes neighbor coordinates, and guards by bounds and unvisited state.","shouldFailWhen":"The code omits neighbor offsets, skips bounds checks, or does not distinguish visited cells.","roles":["current cell","neighbor offsets","neighbor coordinates","unvisited guard"],"mustProve":["Four orthogonal neighbor offsets are considered.","Neighbor coordinates are derived from the current cell.","Neighbors are checked for bounds and unvisited distance."],"mustNotAccept":["A diagonal-only expansion.","Assigning distances without an unvisited guard."],"equivalentVariants":["Use a direction list with four row/column offsets.","Use separate if statements for the four orthogonal neighbors."],"proofSnippets":[{"id":"py-zero-one-matrix-expand-neighbors","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))\n\n        head = 0\n        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n        while head < len(queue):\n            row, col = queue[head]\n            head += 1\n            for dr, dc in directions:\n                nr = row + dr\n                nc = col + dc\n                if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:\n                    pass"}]}},{"id":"enqueue-neighbors","title":"Assign distance and enqueue","description":"When an unvisited neighbor is found, set its distance to current distance plus one and enqueue it.","commonMistakes":["Appending the current cell again","Writing a constant distance instead of current + 1"],"hint":"The first time a cell is discovered by BFS is its nearest-zero distance.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"enqueues_derived_frontier_state","scope":"rot-fresh","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Commit each newly discovered neighbor and add it to the frontier for later expansion.","doneWhen":"The neighbor receives distance dist[row][col] + 1 and that same neighbor coordinate is enqueued.","shouldFailWhen":"The code enqueues the wrong coordinate, fails to update distance, or can enqueue the same cell repeatedly.","roles":["current distance","neighbor distance","frontier enqueue"],"mustProve":["The neighbor distance is derived from the current cell's distance.","The neighbor coordinate is appended to the frontier.","The update happens under the valid-unvisited neighbor guard."],"mustNotAccept":["Enqueuing the old current cell.","Updating distance without adding the neighbor to the queue."],"equivalentVariants":["Set the neighbor distance before enqueuing it.","Use a visited matrix instead of -1 as long as the neighbor is committed before enqueue."],"proofSnippets":[{"id":"py-zero-one-matrix-enqueue-neighbors","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))\n\n        head = 0\n        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n        while head < len(queue):\n            row, col = queue[head]\n            head += 1\n            for dr, dc in directions:\n                nr = row + dr\n                nc = col + dc\n                if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:\n                    dist[nr][nc] = dist[row][col] + 1\n                    queue.append((nr, nc))"}]}},{"id":"return-distances","title":"Return the distance matrix","description":"After BFS finishes, return the completed distance matrix.","commonMistakes":["Returning the original matrix","Returning only the last distance"],"hint":"The output should preserve the matrix shape and replace each cell with its nearest-zero distance.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the matrix that was filled with BFS distances.","doneWhen":"The function returns the distance matrix after the queue traversal is complete.","shouldFailWhen":"The code returns the input matrix unchanged, a scalar, or a partial row.","roles":["distance matrix","returned result"],"mustProve":["The returned value is the distance matrix updated by BFS.","The return occurs after traversal finishes."],"mustNotAccept":["Returning the original binary matrix without distances.","Returning a single distance or queue state."],"equivalentVariants":["Return the distance matrix directly.","Return an equivalent matrix variable that stores the BFS distances."],"proofSnippets":[{"id":"py-zero-one-matrix-return-distances","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))\n\n        head = 0\n        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n        while head < len(queue):\n            row, col = queue[head]\n            head += 1\n            for dr, dc in directions:\n                nr = row + dr\n                nc = col + dc\n                if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:\n                    dist[nr][nc] = dist[row][col] + 1\n                    queue.append((nr, nc))\n\n        return dist"}]}}],"slides":[{"id":"read-the-signal","chapter":"The grid","kind":"info","eyebrow":"Read the problem","title":"How far is each cell from a zero?","workspacePanel":"problem","body":["You get a binary grid of zeros and ones. Replace every cell with its distance to the nearest zero, counting steps up, down, left, or right.","Searching separately from each one-cell repeats the same routes toward the same zeros."]},{"id":"brute-force","chapter":"The slow way","kind":"info","eyebrow":"Start naive","title":"Search outward from every one","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"brute-state","state":{"grid":[[0,0,0],[0,1,0],[1,1,1]],"r":2,"c":1,"labels":{"grid":"mat"}}}]},"body":["The direct reading of the task: for each one cell, run a search outward until it touches a zero, and record how many steps that took.","On the bottom-middle one at (2,1), the search expands a ring of one neighbor, then a ring of two, and stops when it first lands on a zero two steps away."]},{"id":"waste-probe","chapter":"The slow way","kind":"case-probe","eyebrow":"Find the waste","title":"A one-cell search and its neighbor both fan out toward the same zeros. What is repeated?","workspacePanel":"visualizer","summary":"(2,0) searches to the zero above it, and (2,1) searches through that same region right after.","options":[{"id":"same-rings","label":"Both walks re-expand the same cells looking for zeros that are already known to be near","rationale":"Neighboring ones overlap almost entirely in the cells they scan, so each one re-discovers ground its neighbor just covered. The work multiplies with the number of ones.","isCorrect":true},{"id":"nothing","label":"Nothing, each one needs its own independent answer","rationale":"The answers differ, but the paths to reach a zero overlap heavily, so the scanning work is duplicated even though the final numbers are not."},{"id":"only-zeros","label":"Only the zero cells, which get visited twice","rationale":"Every nearby one re-walks the region between it and its nearest zero, so the repeated work includes more than the endpoints."}],"answer":"The same surrounding cells are re-expanded by every nearby one. Each one runs its own fan-out, so overlapping regions are scanned again and again.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"waste-state","state":{"grid":[[0,0,0],[0,1,0],[1,1,1]],"r":2,"c":0,"labels":{"grid":"mat"}}}]}},{"id":"flip-direction","chapter":"The idea","kind":"case-probe","eyebrow":"Find the start","title":"Instead of searching from each one, where should a single shared sweep begin?","workspacePanel":"visualizer","summary":"Every zero already knows its own answer: distance 0.","options":[{"id":"all-zeros","label":"From every zero at once, all of them seeded together as the distance-0 starting ring","rationale":"The zeros are the only cells whose distance is known up front, all at distance 0. Seeding every zero together gives the sweep a starting ring it can grow outward from.","isCorrect":true},{"id":"one-zero","label":"From a single chosen zero, then repeat for the next zero","rationale":"One zero only knows distances for the cells nearest it. A one closer to a different zero would get the wrong distance unless every zero starts together."},{"id":"corner","label":"From the top-left corner, scanning row by row","rationale":"A fixed scan order does not track grid distance. A cell early in the scan can still be far from every zero, so the scan reaches it before its distance is known."}],"answer":"From every zero at once. The zeros are the only cells with a settled distance, so all of them are seeded together as the distance-0 starting ring.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"flip-state","state":{"grid":[[0,0,0],[0,1,0],[1,1,1]],"labels":{"grid":"mat"}}}]}},{"id":"first-arrival","chapter":"The idea","kind":"case-probe","eyebrow":"Find the rule","title":"Several zero-waves can reach the same one. Which arrival is the right distance?","workspacePanel":"visualizer","summary":"The middle one at (1,1) is touched by the zeros above, left, and right of it on the very first ring.","options":[{"id":"first","label":"The first wave to arrive, because all waves grow one step per ring together","rationale":"Every wave expands one ring per step at the same rate, so the first to land came from the nearest zero. That first arrival is exactly the nearest-zero distance.","isCorrect":true},{"id":"smallest-later","label":"Whichever wave arrives with the smallest count, even if it comes later","rationale":"A later arrival has already grown more rings, so its count can only be larger. The first arrival is already the smallest possible distance."},{"id":"sum","label":"The combined reach of every wave that touches it","rationale":"Distance is the steps to one nearest zero. Adding all touching waves would produce a tally instead of a path length."}],"answer":"The first wave to arrive. Waves grow in lockstep, so the first to reach a cell came from its nearest zero and carries the correct distance.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-arrival-state","state":{"grid":[[0,0,0],[0,-1,0],[-1,-1,-1]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[1,0],[1,2]],"frontier":[[2,0],[2,2]],"changed":[],"labels":{"grid":"dist"}}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"grid":[[0,0,0],[0,1,0],[1,1,1]],"labels":{"grid":"mat"}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Seed every zero, sweep outward","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"grid":[[0,0,0],[0,-1,0],[-1,-1,-1]],"frontier":[[0,0],[0,1],[0,2],[1,0],[1,2]],"filled":[[0,0],[0,1],[0,2],[1,0],[1,2]],"changed":[[0,0],[0,1],[0,2],[1,0],[1,2]],"labels":{"grid":"dist"}}}]},"body":["A distance grid starts with each cell marked unreached. Every zero is set to distance 0 and dropped into the queue as the first ring.","Each step takes a queued cell, and any still-unreached neighbor gets that cell’s distance plus one, then joins the queue. Watch the gradient grow on [[0,0,0],[0,1,0],[1,1,1]]."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the sweep","title":"Fill the distance grid","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seed","state":{"grid":[[0,0,0],[0,-1,0],[-1,-1,-1]],"frontier":[[0,0],[0,1],[0,2],[1,0],[1,2]],"filled":[[0,0],[0,1],[0,2],[1,0],[1,2]],"changed":[[0,0],[0,1],[0,2],[1,0],[1,2]],"labels":{"grid":"dist"}}},{"id":"ring-one","state":{"grid":[[0,0,0],[0,1,0],[1,-1,1]],"frontier":[[1,1],[2,0],[2,2]],"filled":[[0,0],[0,1],[0,2],[1,0],[1,2],[1,1],[2,0],[2,2]],"changed":[[1,1],[2,0],[2,2]],"labels":{"grid":"dist"}}},{"id":"ring-two","state":{"grid":[[0,0,0],[0,1,0],[1,2,1]],"r":2,"c":1,"filled":[[0,0],[0,1],[0,2],[1,0],[1,2],[1,1],[2,0],[2,2],[2,1]],"changed":[[2,1]],"labels":{"grid":"dist"}}}]},"beats":[{"id":"seed","title":"The queue holds all five zeros. What distance do they carry?","summary":"Nothing has expanded yet.","prompt":"The five zeros are seeded as the first ring; the four ones are still unreached.","options":[{"id":"zero","label":"0, since a zero is its own nearest zero","rationale":"A zero cell is zero steps from a zero, itself. Seeding every zero at distance 0 makes them the shared starting ring.","isCorrect":true},{"id":"one","label":"1, the first step of the sweep","rationale":"The sweep has not stepped yet. The zeros are the starting line at distance 0; their neighbors become 1 on the first ring."},{"id":"unreached","label":"Unreached, until a wave reaches them","rationale":"The zeros are the waves' sources. Their distance is known immediately, so they start committed at 0."}],"answer":"0. Every zero is its own nearest zero, so all five are seeded at distance 0 as the first ring."},{"id":"ring-one","title":"First ring expands. Which ones get distance 1, and which is still unreached?","summary":"The first expansion starts from all seeded zeros.","prompt":"The edge zeros inspect their neighboring cells.","options":[{"id":"three","label":"(1,1), (2,0), and (2,2) become 1; (2,1) is still unreached","rationale":"Each of those three touches a zero directly, so all become 1. (2,1) borders only ones so far, so no wave has reached it yet.","isCorrect":true},{"id":"all-four","label":"All four ones become 1 this ring","rationale":"(2,1) has no zero neighbor; its neighbors (2,0) and (2,2) only just became 1 this ring, so it cannot be reached until the next one."},{"id":"center-two","label":"(1,1) becomes 1, the bottom row becomes 2","rationale":"A cell’s distance is one more than the cell that reaches it. (2,0) and (2,2) sit next to a distance-0 zero, so they are 1, not 2."}],"answer":"(1,1), (2,0), and (2,2) all become 1, one step from a zero. (2,1) borders only ones, so it waits for the next ring."},{"id":"ring-two","title":"Second ring. What distance does (2,1) take?","summary":"(2,0) and (2,2) are now distance-1 cells in the queue.","prompt":"(2,1) is reached for the first time, by the distance-1 cells beside it.","options":[{"id":"two","label":"2, one more than the distance-1 cell that reaches it","rationale":"Its first wave arrives from (2,0) or (2,2), both at distance 1, so (2,1) commits to 1 + 1 = 2. The nearest zero is two steps away.","isCorrect":true},{"id":"one","label":"1, like the cells around it","rationale":"(2,1) has no zero neighbor; the cells reaching it are themselves at distance 1, so it is one step further out, at 2."},{"id":"three","label":"3, since two waves arrive together","rationale":"Two waves arriving on the same ring still mark a single first arrival at distance 2. Distances do not add when waves meet."}],"answer":"2. The first wave to reach (2,1) comes from a distance-1 cell, so it commits to 2, and the grid is complete."}]},{"id":"overwrite-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can you write a distance to every in-bounds neighbor?","workspacePanel":"trace","summary":"Writing a distance to each in-bounds neighbor passes the simple grids, where every cell only gets reached once. But without checking that a neighbor is still unreached, a later wave overwrites a distance that was already correct, and re-queues the cell. Watch it corrupt a settled value.","pitfall":"The code below assigns dist[row][col] + 1 to every in-bounds neighbor, with no check that the neighbor is still unreached.","whyItMatters":"A neighbor must only take a distance the first time it is reached. Guard the write with dist[nr][nc] == -1 so an already-settled cell, including a zero source, is never overwritten or re-queued.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def updateMatrix(mat: list[list[int]]) -> list[list[int]]:\n    rows = len(mat)\n    cols = len(mat[0])\n    dist = [[0 if mat[row][col] == 0 else rows * cols for col in range(cols)] for row in range(rows)]\n    queue: list[list[int]] = []\n    for row in range(rows):\n        for col in range(cols):\n            if mat[row][col] == 0:\n                queue.append([row, col])\n    head = 0\n    directions: list[list[int]] = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n    while head < len(queue):\n        row, col = queue[head]\n        head += 1\n        for dr, dc in directions:\n            nr = row + dr\n            nc = col + dc\n            if 0 <= nr < rows and 0 <= nc < cols:\n                dist[nr][nc] = dist[row][col] + 1\n                queue.append([nr, nc])\n    return dist","steps":[{"id":"reach-forward","title":"On [[0,1,1]] the sweep reaches forward to (0,2)","codeLine":19,"summary":"dist is [0,1,-1] and (0,1) is being processed. The forward neighbor (0,2) is set to 2. So far the grid is correct.","state":{"grid":[[0,1,2]],"r":0,"c":2,"filled":[[0,0],[0,1],[0,2]],"frontier":[[0,2]],"changed":[[0,2]],"labels":{"grid":"dist"}}},{"id":"guard-passes","title":"The bounds-only check lets the zero source back in","codeLine":18,"summary":"Processing (0,1), the back neighbor (0,0) is in bounds, so this check passes it through, even though (0,0) is a settled zero source.","state":{"grid":[[0,1,2]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2]],"changed":[],"labels":{"grid":"dist"}}},{"id":"overwrite","title":"It overwrites the settled zero","codeLine":19,"summary":"The write sets dist[0][0] to dist[0][1] + 1 = 2, replacing the correct 0 with a bogus 2.","state":{"grid":[[2,1,2]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2]],"labels":{"grid":"dist"},"changed":[[0,0]]}},{"id":"requeue","title":"The corrupted source is queued again","codeLine":20,"summary":"(0,0) is re-queued at the wrong value 2. When the loop reaches it, it will bump (0,1) to 3, and the settled distances unravel instead of finishing at [0,1,2].","state":{"grid":[[2,1,2]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2]],"frontier":[[0,0]],"labels":{"grid":"dist"},"changed":[]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const rows = mat.length;\nconst cols = mat[0].length;\nconst dist = Array.from({ length: rows }, (_, index) => index).map((row) => Array.from({ length: cols }, (_, index) => index).map((col) => (mat[row][col] === 0 ? 0 : (rows * cols))));\nconst queue = [];\nfor (let row = 0; row < rows; row++) {\n    for (let col = 0; col < cols; col++) {\n        if (mat[row][col] === 0) {\n            queue.push([row, col]);\n        }\n    }\n}\nlet head = 0;\nconst directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];\nwhile (head < queue.length) {\n    const [row, col] = queue[head];\n    head++;\n    for (const [dr, dc] of directions) {\n        const nr = row + dr;\n        const nc = col + dc;\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            dist[nr][nc] = (dist[row][col] + 1);\n            queue.push([nr, nc]);\n        }\n    }\n}\nreturn dist;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":19,"18":20,"19":21,"20":22,"21":26},"statementBundles":{"9":{"startLine":8,"endLine":11},"20":{"startLine":22,"endLine":25}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const rows = mat.length;\nconst cols = mat[0].length;\nconst dist = Array.from({ length: rows }, (_, index) => index).map((row) => Array.from({ length: cols }, (_, index) => index).map((col) => (mat[row][col] === 0 ? 0 : (rows * cols))));\nconst queue: Array<Array<number>> = [];\nfor (let row = 0; row < rows; row++) {\n    for (let col = 0; col < cols; col++) {\n        if (mat[row][col] === 0) {\n            queue.push([row, col]);\n        }\n    }\n}\nlet head = 0;\nconst directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];\nwhile (head < queue.length) {\n    const [row, col] = queue[head];\n    head++;\n    for (const [dr, dc] of directions) {\n        const nr = row + dr;\n        const nc = col + dc;\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            dist[nr][nc] = (dist[row][col] + 1);\n            queue.push([nr, nc]);\n        }\n    }\n}\nreturn dist;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":19,"18":20,"19":21,"20":22,"21":26},"statementBundles":{"9":{"startLine":8,"endLine":11},"20":{"startLine":22,"endLine":25}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int rows = mat.size();\nint cols = mat.get(0).size();\nList<List<Integer>> dist = new ArrayList<>();\nfor (int row = 0; row < rows; row++) {\n    List<Integer> items0 = new ArrayList<>();\n    for (int col = 0; col < cols; col++) {\n        items0.add((mat.get(row).get(col) == 0 ? 0 : (rows * cols)));\n    }\n    dist.add(items0);\n}\nList<List<Integer>> queue = new ArrayList<>();\nfor (int row = 0; row < rows; row++) {\n    for (int col = 0; col < cols; col++) {\n        if (mat.get(row).get(col) == 0) {\n            queue.add(new ArrayList<>(List.of(row, col)));\n        }\n    }\n}\nint head = 0;\nList<List<Integer>> directions = new ArrayList<>(Arrays.asList(new ArrayList<>(List.of(1, 0)), new ArrayList<>(List.of(-1, 0)), new ArrayList<>(List.of(0, 1)), new ArrayList<>(List.of(0, -1))));\nwhile (head < queue.size()) {\n    List<Integer> item = queue.get(head);\n    int row = item.get(0);\n    int col = item.get(1);\n    head++;\n    for (List<Integer> direction : directions) {\n        int dr = direction.get(0);\n        int dc = direction.get(1);\n        int nr = row + dr;\n        int nc = col + dc;\n        if (((0 <= nr && nr < rows) && (0 <= nc && nc < cols))) {\n            dist.get(nr).set(nc, (dist.get(row).get(col) + 1));\n            queue.add(new ArrayList<>(List.of(nr, nc)));\n        }\n    }\n}\nreturn dist;","lineMap":{"2":1,"3":2,"4":3,"5":11,"6":12,"7":13,"8":14,"9":15,"10":19,"11":20,"12":21,"13":22,"14":25,"15":26,"16":29,"17":30,"18":31,"19":32,"20":33,"21":37},"statementBundles":{"4":{"startLine":3,"endLine":10},"9":{"startLine":15,"endLine":18},"13":{"startLine":22,"endLine":24},"15":{"startLine":26,"endLine":28},"20":{"startLine":33,"endLine":36}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int rows = mat.Count;\nint cols = mat[0].Count;\nList<List<int>> dist = Enumerable.Range(0, rows).Select(row => Enumerable.Range(0, cols).Select(col => (mat[row][col] == 0 ? 0 : rows * cols)).ToList()).ToList();\nList<List<int>> queue = new();\nfor (int row = 0; row < rows; row++) {\n    for (int col1 = 0; col1 < cols; col1++) {\n        if (mat[row][col1] == 0) {\n            queue.Add(new List<int> { row, col1 });\n        }\n    }\n}\nint head = 0;\nList<List<int>> directions = new() { new List<int> { 1, 0 }, new List<int> { -1, 0 }, new List<int> { 0, 1 }, new List<int> { 0, -1 } };\nwhile (head < queue.Count) {\n    int row = queue[head][0];\n    int col = queue[head][1];\n    head++;\n    foreach (var item in directions) {\n        int dr = item[0];\n        int dc = item[1];\n        int nr = row + dr;\n        int nc = col + dc;\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            dist[nr][nc] = dist[row][col] + 1;\n            queue.Add(new List<int> { nr, nc });\n        }\n    }\n}\nreturn dist;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":12,"11":13,"12":14,"13":15,"14":17,"15":18,"16":21,"17":22,"18":23,"19":24,"20":25,"21":29},"statementBundles":{"9":{"startLine":8,"endLine":11},"13":{"startLine":15,"endLine":16},"15":{"startLine":18,"endLine":20},"20":{"startLine":25,"endLine":28}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int rows = mat.size();\nint cols = mat[0].size();\nvector<vector<int>> dist;\nfor (int row = 0; row < rows; row++) {\n    vector<int> row1;\n    for (int col = 0; col < cols; col++) {\n        row1.push_back((mat[row][col] == 0 ? 0 : (rows * cols)));\n    }\n    dist.push_back(row1);\n}\nvector<vector<int>> queue;\nfor (int row = 0; row < rows; row++) {\n    for (int col = 0; col < cols; col++) {\n        if (mat[row][col] == 0) {\n            queue.push_back(vector<int>{row, col});\n        }\n    }\n}\nsize_t head = 0;\nvector<vector<int>> directions{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\nwhile (head < queue.size()) {\n    auto values = queue[static_cast<int>(head)];\n    int row = values[0];\n    int col = values[1];\n    head++;\n    for (vector<int> item : directions) {\n        int dr = item[0];\n        int dc = item[1];\n        int nr = row + dr;\n        int nc = col + dc;\n        if (((0 <= nr && nr < rows) && (0 <= nc && nc < cols))) {\n            dist[nr][nc] = (dist[row][col] + 1);\n            queue.push_back(vector<int>{nr, nc});\n        }\n    }\n}\nreturn dist;","lineMap":{"2":1,"3":2,"4":3,"5":11,"6":12,"7":13,"8":14,"9":15,"10":19,"11":20,"12":21,"13":22,"14":25,"15":26,"16":29,"17":30,"18":31,"19":32,"20":33,"21":37},"statementBundles":{"4":{"startLine":3,"endLine":10},"9":{"startLine":15,"endLine":18},"13":{"startLine":22,"endLine":24},"15":{"startLine":26,"endLine":28},"20":{"startLine":33,"endLine":36}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The sweep filled the sample grid by growing one ring per step until every one had a distance.","Two shapes are worth a look before coding: a grid that is a single row, and a one cell that two different zeros can both reach."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"grid":[[0,0,0],[0,1,0],[1,2,1]],"filled":[[0,0],[0,1],[0,2],[1,0],[1,2],[1,1],[2,0],[2,2],[2,1]],"labels":{"grid":"dist"},"changed":[]}}]}},{"id":"single-row-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"The grid is a single row. Does the sweep still work?","workspacePanel":"visualizer","summary":"On [[1,0,1,1]] the only zero sits at (0,1), and every move is left or right.","options":[{"id":"same-bounds","label":"Yes, the same bounds check rejects the vertical moves and the horizontal sweep fills the row","rationale":"Up and down land outside the grid, so the bounds check drops them. Left and right stay in range, so the row fills 1, 0, 1, 2 outward from the zero.","isCorrect":true},{"id":"needs-special","label":"No, a single row needs a separate left-right-only routine","rationale":"No special case is needed: the bounds check already discards the vertical neighbors, leaving exactly the horizontal expansion."},{"id":"breaks","label":"No, the vertical neighbors read out of bounds and crash","rationale":"The bounds check runs before any read, so an out-of-range neighbor is skipped, never accessed."}],"answer":"Yes. The bounds check rejects the off-grid vertical moves, and the row fills horizontally to 1, 0, 1, 2 from the single zero.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-row-state","state":{"grid":[[1,0,1,1]],"r":0,"c":1,"filled":[[0,1]],"labels":{"grid":"dist"},"changed":[]}}]}},{"id":"two-source-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"A one sits between two zeros. What distance does it get?","workspacePanel":"visualizer","summary":"On [[0,1,0]] the middle one at (0,1) borders a zero on each side.","options":[{"id":"one-once","label":"1, committed on the first arrival and never overwritten by the second","rationale":"Both zeros reach it on the first ring at distance 1. The first arrival commits it to 1, and the unreached check makes the second arrival a no-op.","isCorrect":true},{"id":"two","label":"2, since two zeros both reach it","rationale":"Each zero is one step away, so the distance is 1. Two waves arriving does not add the distances together."},{"id":"overwritten","label":"1, then overwritten back to a fresh value by the second zero","rationale":"The unreached guard stops the second wave from touching an already-settled cell, so the committed 1 stands."}],"answer":"1. The first zero reaches it at distance 1 and commits the value; the unreached check turns the second zero’s arrival into a no-op.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-source-state","state":{"grid":[[0,1,0]],"r":0,"c":1,"filled":[[0,0],[0,1],[0,2]],"labels":{"grid":"dist"},"changed":[[0,1]]}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Build the distance sweep","summary":"Commit a distance only on first arrival, so the nearest zero always wins.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[0,0,0],[0,-1,0],[-1,-1,-1]],"frontier":[[0,0],[0,1],[0,2],[1,0],[1,2]],"filled":[[0,0],[0,1],[0,2],[1,0],[1,2]],"labels":{"grid":"dist"},"changed":[]}}]},"body":["Mark every cell unreached, set each zero to distance 0, and seed the queue with all of them. Then sweep: take a queued cell, and for each still-unreached neighbor, give it one more than the current cell and queue it. Return the filled grid when the queue empties."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the distance sweep","eyebrow":"Code the rule","summary":"Seed zero sources, expand the queue, write first-visit distances, then return the matrix.","workspacePanel":"code","checkpoints":[{"id":"init-frontier","title":"Seed all zero cells","description":"Mark every cell unreached, set each zero cell to distance 0, and enqueue those zero cells as the starting ring.","commonMistakes":["Seeding only the first zero instead of every zero","Leaving zero cells marked unreached"],"hint":"Every zero is a starting source at distance 0; the ones stay unreached until a wave arrives.","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":"Initialize BFS with every source cell and a distance grid that marks unreached cells.","doneWhen":"All zero cells are set to distance 0 and enqueued before the sweep loop, with other cells marked unreached.","shouldFailWhen":"The queue is missing some zero cells, distances are not initialized, or the sweep starts from a one cell.","roles":["distance matrix","frontier queue","zero source cells"],"mustProve":["A frontier queue is initialized before traversal.","The matrix is scanned for zero-valued source cells.","Each source is marked with distance 0 and enqueued."],"mustNotAccept":["Enqueuing only one source when multiple zeros exist.","Starting from unreached one cells."],"equivalentVariants":["Use a list with a head index or a deque as the BFS queue.","Use any distance or visited matrix that marks source cells as distance 0."],"proofSnippets":[{"id":"py-zero-one-matrix-init-frontier","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))"}]}},{"id":"bfs-loop","title":"Sweep the queue in order","description":"Take cells off the frontier in the order they were added, so the first time a cell is reached stays final.","commonMistakes":["Taking cells from the end like a stack, breaking the ring order","Rescanning the whole grid instead of advancing the frontier"],"hint":"First-in, first-out order is what guarantees the first arrival at a cell is from its nearest zero.","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 traversal from the frontier until every reachable cell has been processed, preserving FIFO first-arrival semantics.","doneWhen":"The code loops while queued cells remain, takes the next queued cell in FIFO order, and never treats an already-reached cell as a fresh frontier item.","shouldFailWhen":"The queue is never consumed, traversal uses LIFO behavior, or already-assigned cells can be reprocessed as newly reached cells.","roles":["frontier queue","FIFO order","current cell","first discovery"],"mustProve":["The loop condition depends on frontier availability.","Each iteration obtains one queued cell in FIFO order.","Already-reached cells are not converted back into fresh frontier entries."],"mustNotAccept":["A full matrix scan in place of a queue-driven traversal.","Taking from the end as the primary traversal step."],"equivalentVariants":["Use a head index that advances over the queue list.","Use a deque and take from the front each iteration."],"proofSnippets":[{"id":"py-zero-one-matrix-bfs-loop","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))\n\n        head = 0\n        while head < len(queue):\n            row, col = queue[head]\n            head += 1"}]}},{"id":"expand-neighbors","title":"Check four neighboring cells","description":"For each cell taken off the queue, look at its four orthogonal neighbors and keep only those in bounds and still unreached.","commonMistakes":["Including diagonal moves","Reading a neighbor before checking the grid bounds","Re-reaching cells whose distance is already known"],"hint":"Only a neighbor that is in bounds and still unreached (dist == -1) should receive a new distance.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"check-neighbors","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Derive valid neighbor coordinates from each current cell during BFS expansion.","doneWhen":"The code iterates over orthogonal offsets, computes neighbor coordinates, and guards by bounds and unreached state.","shouldFailWhen":"The code omits neighbor offsets, skips bounds checks, or does not distinguish reached cells.","roles":["current cell","neighbor offsets","neighbor coordinates","unvisited guard"],"mustProve":["Four orthogonal neighbor offsets are considered.","Neighbor coordinates are derived from the current cell.","Neighbors are checked for bounds and unreached distance."],"mustNotAccept":["A diagonal-only expansion.","Assigning distances without an unreached guard."],"equivalentVariants":["Use a direction list with four row and column offsets.","Use separate if statements for the four orthogonal neighbors."],"proofSnippets":[{"id":"py-zero-one-matrix-expand-neighbors","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))\n\n        head = 0\n        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n        while head < len(queue):\n            row, col = queue[head]\n            head += 1\n            for dr, dc in directions:\n                nr = row + dr\n                nc = col + dc\n                if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:\n                    pass"}]}},{"id":"enqueue-neighbors","title":"Commit distance and enqueue","description":"When a neighbor is in bounds and unreached, set its distance to the current cell plus one and add it to the queue.","commonMistakes":["Re-adding the current cell instead of the neighbor","Writing a constant distance instead of current + 1"],"hint":"The first time a cell is reached is its nearest-zero distance, so commit it then and queue it once.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"enqueues_derived_frontier_state","scope":"rot-fresh","readMode":"bfs-queue-value-query-v1"}]},"semanticSpec":{"intent":"Commit each newly reached neighbor and add it to the frontier for later expansion.","doneWhen":"The neighbor receives distance dist[row][col] + 1 and that same neighbor coordinate is enqueued.","shouldFailWhen":"The code enqueues the wrong coordinate, fails to update distance, or can enqueue the same cell repeatedly.","roles":["current distance","neighbor distance","frontier enqueue"],"mustProve":["The neighbor distance is derived from the current cell’s distance.","The neighbor coordinate is appended to the frontier.","The update happens under the valid-unreached neighbor guard."],"mustNotAccept":["Enqueuing the old current cell.","Updating distance without adding the neighbor to the queue."],"equivalentVariants":["Set the neighbor distance before enqueuing it.","Use a visited matrix instead of -1 as long as the neighbor is committed before enqueue."],"proofSnippets":[{"id":"py-zero-one-matrix-enqueue-neighbors","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))\n\n        head = 0\n        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n        while head < len(queue):\n            row, col = queue[head]\n            head += 1\n            for dr, dc in directions:\n                nr = row + dr\n                nc = col + dc\n                if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:\n                    dist[nr][nc] = dist[row][col] + 1\n                    queue.append((nr, nc))"}]}},{"id":"return-distances","title":"Return the distance grid","description":"After the queue empties, return the completed distance grid.","commonMistakes":["Returning the original binary matrix","Returning a single distance instead of the grid"],"hint":"The result keeps the grid shape, with each cell replaced by its nearest-zero distance.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the grid that was filled with BFS distances.","doneWhen":"The function returns the distance grid after the queue traversal is complete.","shouldFailWhen":"The code returns the input matrix unchanged, a scalar, or a partial row.","roles":["distance matrix","returned result"],"mustProve":["The returned value is the distance grid updated by BFS.","The return occurs after traversal finishes."],"mustNotAccept":["Returning the original binary matrix without distances.","Returning a single distance or queue state."],"equivalentVariants":["Return the distance grid directly.","Return an equivalent grid variable that stores the BFS distances."],"proofSnippets":[{"id":"py-zero-one-matrix-return-distances","language":"python","code":"class Solution:\n    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n        rows = len(mat)\n        cols = len(mat[0])\n        dist = [[-1] * cols for _ in range(rows)]\n        queue = []\n\n        for r in range(rows):\n            for c in range(cols):\n                if mat[r][c] == 0:\n                    dist[r][c] = 0\n                    queue.append((r, c))\n\n        head = 0\n        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n        while head < len(queue):\n            row, col = queue[head]\n            head += 1\n            for dr, dc in directions:\n                nr = row + dr\n                nc = col + dc\n                if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:\n                    dist[nr][nc] = dist[row][col] + 1\n                    queue.append((nr, nc))\n\n        return dist"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Seed every zero at once, sweep outward, and the first arrival at each cell is its nearest-zero distance.","workspacePanel":"code","body":["This is a multi-source breadth-first sweep: all zeros start as distance-0 sources together, and one ring of distance grows per step.","Each one cell takes the distance of the first wave to reach it, committed once and never overwritten, which is exactly its nearest-zero distance."],"takeaways":[{"title":"All sources start together","body":"Seeding every zero before the sweep makes a cell's first arrival come from its nearest zero."},{"title":"First arrival is final","body":"The unreached guard commits a distance once, so a later wave can never overwrite a value that was already shortest."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
