{"id":"walls-and-gates","title":"Walls and Gates","difficulty":"medium","patterns":["graph-bfs"],"primaryConcept":"graph-grid-fill","concepts":["graph-grid-fill"],"problemForm":"core","companies":["Meta","Amazon","Google","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"rooms","sizeMetric":"matrix-cells","sizes":[4,9,16,25],"valueRange":{"min":-1,"max":2147483647}},"description":"You are given a grid `rooms` where:\n\n- `-1` is a wall\n- `0` is a gate\n- `2147483647` means an empty room. We will write this as `INF` in examples.\n\nFill each empty room with the distance to its nearest gate. If a room cannot reach any gate, leave it as `INF`.\n\nReturn the updated grid.","examples":[{"input":"rooms = [[INF,-1,0,INF],[INF,INF,INF,-1],[INF,-1,INF,-1],[0,-1,INF,INF]]","output":"[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]","explanation":"Distances spread outward from both gates at the same time."},{"input":"rooms = [[0,INF],[INF,INF]]","output":"[[0,1],[1,2]]","explanation":"Each empty room receives its Manhattan distance from the single gate."}],"constraints":[{"id":"1-m-n-250","text":"1 <= m, n <= 250"},{"id":"rooms-i-j-is-1-0-or-2147483647","text":"rooms[i][j] is -1, 0, or 2147483647","check":{"kind":"domain","target":"rooms","selector":"nestedArrayItems","allowed":[-1,0,2147483647],"rectangular":true}}],"starterCode":"class Solution:\n    def wallsAndGates(self, rooms: list[list[int]]) -> list[list[int]]:\n        # Your code here\n        pass","functionName":"wallsAndGates","testCases":[{"id":"1","input":{"rooms":[[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]},"expected":[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]],"description":"Canonical multi-source BFS sample."},{"id":"2","input":{"rooms":[[0,2147483647],[2147483647,2147483647]]},"expected":[[0,1],[1,2]],"description":"Single gate fills a small open grid."},{"id":"3","input":{"rooms":[[2147483647,-1,0]]},"expected":[[2147483647,-1,0]],"description":"A wall keeps the room unreachable."},{"id":"4","input":{"rooms":[[0]]},"expected":[[0]],"description":"Single gate cell."},{"id":"hidden-1","input":{"rooms":[[0,2147483647,2147483647],[2147483647,-1,2147483647],[2147483647,2147483647,0]]},"expected":[[0,1,2],[1,-1,1],[2,1,0]],"description":"Two gates meet around a wall."},{"id":"hidden-2","input":{"rooms":[[-1,0],[2147483647,-1]]},"expected":[[-1,0],[2147483647,-1]],"description":"A wall-isolated room remains unchanged."},{"id":"hidden-3","input":{"rooms":[[2147483647,2147483647],[2147483647,2147483647]]},"expected":[[2147483647,2147483647],[2147483647,2147483647]],"description":"A grid with no gates stays unchanged."},{"id":"hidden-4","input":{"rooms":[[-1,-1],[-1,-1]]},"expected":[[-1,-1],[-1,-1]],"description":"All-wall grids should not enqueue anything."},{"id":"hidden-5","input":{"rooms":[[2147483647,0,2147483647,2147483647,0]]},"expected":[[1,0,1,1,0]],"description":"A one-row grid uses the nearest gate from either side."},{"id":"hidden-6","input":{"rooms":[[2147483647],[2147483647],[0],[2147483647]]},"expected":[[2],[1],[0],[1]],"description":"A one-column grid fills vertically from the gate."},{"id":"topup-no-gate-rooms-remain-infinite","input":{"rooms":[[2147483647,-1],[2147483647,2147483647]]},"expected":[[2147483647,-1],[2147483647,2147483647]],"description":"Without a gate, reachable rooms remain at infinity."},{"id":"topup-corridor-two-gates","input":{"rooms":[[2147483647,2147483647,0],[-1,2147483647,-1],[0,2147483647,2147483647]]},"expected":[[2,1,0],[-1,2,-1],[0,1,2]],"description":"Two gates fill a bent corridor around walls."}],"hints":[{"level":1,"content":"Start BFS from every gate, not from every empty room."},{"level":2,"content":"When an empty room is first reached, the current distance is the shortest possible distance to any gate."},{"level":3,"content":"Use the updated distance in the current cell to assign `distance + 1` to each newly reached neighbor."}],"guidedFlow":{"version":2,"progressRevision":"walls-and-gates-2026-07-19-reverse-shared-search-before-multisource-bfs","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","name":"Multi-source BFS from gates","summary":"Put every gate into the queue, then expand into empty rooms and write distance plus one.","decisionReason":"All gates expand in lockstep, so each room is claimed once by its nearest gate in a single O(m*n) sweep over the grid.","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Runs in O(m*n) time and uses O(m*n) space."],"isOptimal":true},{"id":"bfs-from-each-room","name":"BFS from each empty room","summary":"Search for a gate separately from every empty room.","decisionReason":"Every empty room runs its own search, so a cell on a shared path to a gate is re-walked once per room behind it: roughly (m*n) searches over (m*n) cells.","complexity":{"time":"O(m^2*n^2)","space":"O(m*n)"},"tradeoffs":["Runs in O(m^2*n^2) time and uses O(m*n) space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-frontier","title":"Seed all gates","description":"Scan the grid and enqueue every gate as an initial BFS source.","commonMistakes":["Starting from only the first gate","Starting BFS from empty rooms"],"hint":"All gates should enter the queue before expansion starts.","semanticSpec":{"intent":"Initialize the BFS frontier and auxiliary state.","doneWhen":"The queue is initialized from the grid before traversal.","shouldFailWhen":"No frontier is created before the BFS loop.","roles":["frontier queue","gate cells"],"mustProve":["BFS frontier initialization exists."],"mustNotAccept":["A scan with no queued frontier."],"equivalentVariants":["Use a list with a head index or a deque/queue structure."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"initializes_frontier_and_aux_state","scope":"init-queue","readMode":"bfs-queue-value-query-v1"}]}},{"id":"bfs-loop","title":"Process the frontier","description":"Loop while queued cells remain and pop the next room to expand.","commonMistakes":["Using one pass over the grid instead of BFS","Never advancing the queue head"],"hint":"The loop should continue until every reachable room has been claimed.","semanticSpec":{"intent":"Drive the BFS traversal loop.","doneWhen":"The code loops while the frontier is non-empty.","shouldFailWhen":"Queued cells are never processed.","roles":["frontier queue","current cell"],"mustProve":["The frontier loop is driven by queued cells."],"mustNotAccept":["A fixed number of expansion passes."],"equivalentVariants":["Use `while queue`, `while head < len(queue)`, or equivalent."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"loops_while_frontier_non_empty","scope":"bfs-loop","readMode":"bfs-queue-value-query-v1"}]}},{"id":"expand-neighbors","title":"Check neighboring rooms","description":"For each current cell, inspect the four adjacent cells and keep only in-bounds empty rooms.","commonMistakes":["Skipping one direction","Walking through walls"],"hint":"Only `INF` cells should be filled and enqueued.","semanticSpec":{"intent":"Expand valid frontier neighbors.","doneWhen":"The BFS loop checks adjacent grid positions with bounds and room-state guards.","shouldFailWhen":"Neighbors are not inspected from each popped cell.","roles":["current cell","neighbor cell","grid bounds"],"mustProve":["Neighbors are expanded from the BFS frontier."],"mustNotAccept":["Updating arbitrary cells without adjacency."],"equivalentVariants":["Use a direction array or explicit four-neighbor checks."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"check-neighbors","readMode":"bfs-queue-value-query-v1"}]}},{"id":"enqueue-neighbors","title":"Fill and enqueue each reached room, then return the grid","description":"Assign each newly reached room `current + 1` and enqueue it so it spreads the next ring. After the loop drains, return the same grid you filled in place.","commonMistakes":["Enqueuing without marking the room","Writing a constant distance"],"hint":"The current cell already stores the shortest distance to a gate; each written neighbor continues the BFS frontier.","semanticSpec":{"intent":"Enqueue derived frontier cells after mutation.","doneWhen":"A newly filled room is added to the frontier so its own ring spreads later.","shouldFailWhen":"Rooms are filled but not enqueued for propagation.","roles":["distance value","neighbor payload"],"mustProve":["Derived neighbor state is enqueued."],"mustNotAccept":["Only modifying the first layer."],"equivalentVariants":["Store distance in the grid or in a paired distance payload."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"enqueues_derived_frontier_state_and_returns_mutated_input","scope":"rot-fresh","readMode":"bfs-queue-value-query-v1","expected":{"param":"rooms"}}]}}],"slides":[{"id":"read-the-problem","chapter":"The grid","kind":"info","eyebrow":"Read the problem","title":"Fill every room with its distance to the nearest gate","workspacePanel":"problem","body":["You get a grid where each cell is a wall (-1), a gate (0), or an empty room (INF, written for a very large number). Fill each empty room with the number of steps to the nearest gate, moving up, down, left, or right. A room walled off from every gate stays INF.","Walls block movement, and several gates can exist at once."]},{"id":"brute-force","chapter":"The obvious way","kind":"info","eyebrow":"Start naive","title":"Search outward from every empty room","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"brute-state","state":{"grid":[[0,2147483647,2147483647,2147483647],[2147483647,-1,-1,0]],"r":0,"c":1,"labels":{"grid":"rooms"}}}]},"body":["The direct reading of the task: stand in each empty room, search outward ring by ring until you bump into a gate, and record how far you walked.","Room (0,1) searches and lands on the gate at (0,0) one step away. Then room (0,2) starts its own search from scratch and re-walks the same ground to reach the same gate. Every empty room runs its own search this way."]},{"id":"waste-probe","chapter":"The obvious way","kind":"case-probe","eyebrow":"Count the cost","title":"What does a per-room search repeat?","summary":"Rooms (0,1), (0,2), and (0,3) each launch their own search toward the top-left gate, crossing the same corridor at (0,1) and (0,2) on the way.","workspacePanel":"visualizer","options":[{"id":"rewalks","label":"It re-walks the same cells, once per starting room","rationale":"Each room sweeps the grid again to find a gate, so a cell on the way to a gate is crossed once for every room behind it. That is the (m*n) starts times (m*n) sweep that makes it slow.","isCorrect":true},{"id":"nothing","label":"Nothing, each search visits different cells","rationale":"Neighbouring rooms reach the same gate over overlapping paths, so the cells between them and that gate are visited by every one of those searches.","isCorrect":false},{"id":"gates-only","label":"It only repeats work at the gates themselves","rationale":"The repetition runs along the whole path to a gate. Every cell between a room and its gate is re-crossed by each room behind it.","isCorrect":false}],"answer":"It re-walks the same cells once per starting room. The paths from nearby rooms to a shared gate overlap, so the search redoes that overlap again and again.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"waste-state","state":{"grid":[[0,2147483647,2147483647,2147483647],[2147483647,-1,-1,0]],"filled":[[0,1],[0,2]],"labels":{"grid":"rooms"}}}]}},{"id":"approach-selection","chapter":"The trick","kind":"case-probe","eyebrow":"Reuse the shared paths","title":"Where should one shared expansion begin so nearby rooms stop repeating the same path?","summary":"Every room-to-gate path ends at a gate, and nearby rooms share cells near that destination.","workspacePanel":"visualizer","options":[{"id":"from-all-gates","label":"Begin at every gate and spread outward into the rooms","rationale":"Reversing the shared paths lets one expansion from a gate serve every room around it. Starting from all gates lets their work share the grid instead of restarting from each room.","isCorrect":true},{"id":"from-each-room","label":"Keep beginning a separate search at every empty room","rationale":"That is the repeated work we measured: neighboring rooms re-walk the same cells on their way to a gate."},{"id":"from-walls","label":"Begin at the walls and spread into both sides","rationale":"Walls block paths; they do not provide a distance target or a route rooms can use to reach a gate."}],"answer":"Reverse the shared searches: begin at every gate and expand into the rooms. That turns many room-by-room searches into one expansion over the grid. With several gates spreading, we still need to prove which distance a room receives first.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"grid":[[0,2147483647,2147483647,2147483647],[2147483647,-1,-1,0]],"labels":{"grid":"rooms"}}}]}},{"id":"flip-direction","chapter":"The trick","kind":"case-probe","eyebrow":"Flip the search","title":"If the gates spread outward instead, when is a room first reached?","summary":"Every gate spreads outward together, one ring per step. Room (0,3) is one step from the gate at (1,3) and three steps from the gate at (0,0).","workspacePanel":"visualizer","options":[{"id":"nearest-first","label":"By the nearest gate, so its first arrival is already the shortest distance","rationale":"Rings grow one step at a time from all gates at once, so the first ring to touch a room came from the closest gate. (0,3) is reached on ring 1 by the (1,3) gate, before the (0,0) gate could arrive on ring 3.","isCorrect":true},{"id":"farthest","label":"By the farthest gate, since its ring is widest","rationale":"A wider ring takes more steps to arrive, so it reaches a room later. The first arrival comes from the nearest gate.","isCorrect":false},{"id":"order-seeded","label":"By whichever gate was seeded first into the queue","rationale":"Seed order does not decide distance: all gates expand in lockstep ring by ring, so the room is claimed by the gate fewest steps away, regardless of queue order.","isCorrect":false}],"answer":"By the nearest gate. Rings from every gate grow together, so the first ring to reach a room came from the closest gate and that first distance is already the shortest. (0,3) is claimed at 1 from (1,3), never 3 from (0,0).","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"flip-state","state":{"grid":[[0,2147483647,2147483647,2147483647],[2147483647,-1,-1,0]],"frontier":[[0,0],[1,3]],"labels":{"grid":"rooms"}}}]}},{"id":"first-write-wins","chapter":"The trick","kind":"case-probe","eyebrow":"Lock the rule","title":"Do we have to compare distances from every gate to each room?","summary":"The gates have spread one ring: (0,1), (1,0), and (0,3) now hold 1, and they sit in the queue ready to write the next ring of 2s.","workspacePanel":"visualizer","options":[{"id":"no-compare","label":"No: arrivals come in increasing-distance order, so the first write to a room is already the smallest","rationale":"Because every gate advances exactly one ring per step, rooms are reached in nondecreasing distance order across the whole queue. So the first time a room is written, no later arrival can carry a smaller number. Writing once and never overwriting is enough, with no min() to track.","isCorrect":true},{"id":"min-per-room","label":"Yes: for each room, take the minimum over the distances from all gates and keep the smallest","rationale":"That recomputes what the ring order already gives you for free. Since arrivals are in increasing-distance order, the first one to land is the minimum, so an explicit per-room minimum is wasted work.","isCorrect":false},{"id":"sequential-gates","label":"Yes: run a full spread from one gate, then another, and overwrite a room whenever a smaller value shows up","rationale":"Spreading gates one at a time breaks the single shared ring order, which is exactly why you would then need overwrite comparisons. Advancing all gates together keeps arrivals sorted, so no overwrite is ever needed.","isCorrect":false}],"answer":"No comparison is needed. With every gate advancing one ring per step, rooms are reached in increasing-distance order, so a room's first write is automatically its smallest distance. Write each room once and never overwrite.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-write-state","state":{"grid":[[0,1,2147483647,1],[1,-1,-1,0]],"filled":[[0,1],[1,0],[0,3]],"frontier":[[0,1],[1,0],[0,3]],"labels":{"grid":"rooms"}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Seed the gates, spread ring by ring","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"grid":[[0,2147483647,2147483647,2147483647],[2147483647,-1,-1,0]],"frontier":[[0,0],[1,3]],"labels":{"grid":"rooms"}}}]},"body":["The queue starts holding every gate. Each gate keeps the distance it carries, starting at 0.","Take the front cell off the queue, and for each still-empty neighbour write the current distance plus one, then add that neighbour to the queue so it spreads next.","When the queue empties, every reachable room holds its nearest-gate distance and walled-off rooms are still INF."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the spread","title":"Trace the distances spreading","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ring-one","state":{"grid":[[0,1,2147483647,1],[1,-1,-1,0]],"frontier":[[0,1],[1,0],[0,3]],"labels":{"grid":"rooms"}}},{"id":"claim-0-3","state":{"grid":[[0,1,2147483647,1],[1,-1,-1,0]],"r":0,"c":3,"filled":[[0,3]],"labels":{"grid":"rooms"}}},{"id":"ring-two","state":{"grid":[[0,1,2,1],[1,-1,-1,0]],"frontier":[[0,2]],"labels":{"grid":"rooms"}}}]},"beats":[{"id":"ring-one","title":"Step 1: the gates spread one ring. Which rooms get 1?","summary":"Both gates sit in the queue carrying distance 0.","prompt":"Each gate writes its distance plus one into its empty neighbours.","options":[{"id":"three-ones","label":"Cells (0,1), (1,0), and (0,3) all become 1","rationale":"The (0,0) gate fills (0,1) and (1,0); the (1,3) gate fills (0,3). Each is one step from a gate, so each becomes 1 and joins the next ring.","isCorrect":true},{"id":"every-room","label":"Every empty room becomes 1","rationale":"A ring only reaches cells directly beside the current frontier. Room (0,2) is not adjacent to any gate, so it is still a ring away.","isCorrect":false},{"id":"only-left","label":"Only the rooms beside the top-left gate","rationale":"Both gates spread in the same ring. The (1,3) gate fills (0,3) now.","isCorrect":false}],"answer":"Rooms (0,1), (1,0), and (0,3) become 1. Both gates spread together, so every cell one step from a gate is filled in this ring."},{"id":"claim-0-3","title":"Step 2: which gate claims room (0,3), and at what distance?","summary":"Room (0,3) has already been filled with 1.","prompt":"A later ring from (0,0) reaches the same room.","options":[{"id":"one-near","label":"1, from the near gate at (1,3)","rationale":"The (1,3) gate is one step away and reaches (0,3) on the first ring. That first arrival is the nearest distance, so (0,3) holds 1.","isCorrect":true},{"id":"three-far","label":"3, from the top-left gate","rationale":"The top-left gate is three steps away and arrives later. The room was already claimed at 1 by the nearer gate, so the later ring skips it.","isCorrect":false},{"id":"two-avg","label":"2, averaging the two gates","rationale":"Distance is the number of steps to the nearest gate. (0,3) is one step from (1,3), so it is 1.","isCorrect":false}],"answer":"1, from the near gate at (1,3). The first ring to reach (0,3) came from the closest gate, so its first distance is already the shortest."},{"id":"ring-two","title":"Step 3: the next ring reaches (0,2). What does it hold?","summary":"Room (0,1) holds 1 and now spreads to its empty neighbour (0,2).","prompt":"Room (0,2) is filled from a cell holding 1.","options":[{"id":"two","label":"2, one more than the cell that reached it","rationale":"Room (0,1) holds 1, so its still-empty neighbour (0,2) gets 1 plus one, which is 2. The walls at (1,1) and (1,2) stop any other path.","isCorrect":true},{"id":"one","label":"1, the same as its neighbour","rationale":"A neighbour is one step farther, so it is the current distance plus one. (0,2) becomes 2.","isCorrect":false},{"id":"inf","label":"It stays INF because walls surround it","rationale":"Room (0,2) has an open neighbour at (0,1) holding 1, so the ring reaches it. It is filled with 2.","isCorrect":false}],"answer":"2. Room (0,1) holds 1 and fills its empty neighbour (0,2) with 1 plus one. The grid is now [[0,1,2,1],[1,-1,-1,0]]."}]},{"id":"overwrite-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could you fill any neighbour that is not a wall or gate?","summary":"Tempting to drop the still-empty test and just fill every neighbour that is not a wall or gate. On a single-gate grid this still passes, since each room is reached only once. But that test is the only record that a room was already claimed by an earlier ring. Watch what a second gate's ring does once that record is gone.","workspacePanel":"trace","pitfall":"The code below fills any neighbour that is not a wall or gate, without checking whether the room is still empty.","whyItMatters":"Rings arrive nearest-gate first, so a room is correct the moment it is first filled. Without the still-empty guard, the next ring from a farther gate overwrites that correct value with a larger one, and the room keeps re-entering the queue. Fill a room only while it still holds INF.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def wallsAndGates(rooms: list[list[int]]) -> list[list[int]]:\n    from collections import deque\n    rows, cols = len(rooms), len(rooms[0])\n    queue = deque()\n    for r in range(rows):\n        for c in range(cols):\n            if rooms[r][c] == 0:\n                queue.append((r, c))\n\n    def neighbors(r: int, c: int, rows: int, cols: int) -> list[tuple[int, int]]:\n        result: list[tuple[int, int]] = []\n        for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n            nr, nc = r + dr, c + dc\n            if 0 <= nr < rows and 0 <= nc < cols:\n                result.append((nr, nc))\n        return result\n\n    while queue:\n        row, col = queue.popleft()\n        for nr, nc in neighbors(row, col, rows, cols):\n            if rooms[nr][nc] != -1 and rooms[nr][nc] != 0:\n                rooms[nr][nc] = rooms[row][col] + 1\n                queue.append((nr, nc))\n    return rooms","steps":[{"id":"near-fills","title":"The near gate fills (0,3) with 1","codeLine":22,"summary":"rooms = [[0,INF,INF,INF],[INF,-1,-1,0]]. The (1,3) gate reaches (0,3) on the first ring and writes 1, the correct nearest distance.","state":{"grid":[[0,1,2147483647,1],[1,-1,-1,0]],"r":0,"c":3,"filled":[[0,3]],"labels":{"grid":"rooms"}}},{"id":"far-arrives","title":"A later ring arrives at (0,3) carrying 3","codeLine":21,"summary":"The ring from the far gate reaches (0,3) holding 3. The guard only rejects walls and gates, so a filled room passes the test.","state":{"grid":[[0,1,2,1],[1,-1,-1,0]],"r":0,"c":2,"filled":[[0,3]],"labels":{"grid":"rooms"}}},{"id":"overwritten","title":"It overwrites the correct 1 with 3","codeLine":22,"summary":"Room (0,3) is rewritten from 1 to 3 and re-enqueued. The nearest-gate distance is lost and the room will keep churning.","state":{"grid":[[0,1,2,3],[1,-1,-1,0]],"r":0,"c":3,"filled":[[0,3]],"labels":{"grid":"rooms"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const [rows, cols] = [rooms.length, rooms[0].length];\nconst queue = new Deque([]);\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (rooms[r][c] === 0) {\n            queue.pushBack([r, c]);\n        }\n    }\n}\nfunction neighbors(r, c, rows, cols) {\n    const result = [];\n    for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {\n        const [nr, nc] = [(r + dr), (c + dc)];\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            result.push([nr, nc]);\n        }\n    }\n    return result;\n}\nwhile (queue.size() > 0) {\n    const [row, col] = queue.popFront();\n    for (const [nr, nc] of neighbors(row, col, rows, cols)) {\n        if (rooms[nr][nc] !== -1 && rooms[nr][nc] !== 0) {\n            rooms[nr][nc] = (rooms[row][col] + 1);\n            queue.pushBack([nr, nc]);\n        }\n    }\n}\nreturn rooms;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":5,"8":6,"11":11,"12":12,"13":13,"14":14,"15":15,"16":18,"18":20,"19":21,"20":22,"21":23,"22":24,"23":25,"24":29},"statementBundles":{"8":{"startLine":6,"endLine":10},"15":{"startLine":15,"endLine":17},"16":{"startLine":18,"endLine":19},"23":{"startLine":25,"endLine":28}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const [rows, cols] = [rooms.length, rooms[0].length];\nconst queue: Deque<[number, number]> = new Deque([]);\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (rooms[r][c] === 0) {\n            queue.pushBack([r, c]);\n        }\n    }\n}\nfunction neighbors(r: number, c: number, rows: number, cols: number): Array<[number, number]> {\n    const result: Array<[number, number]> = [];\n    for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {\n        const [nr, nc] = [(r + dr), (c + dc)];\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            result.push([nr, nc]);\n        }\n    }\n    return result;\n}\nwhile (queue.size() > 0) {\n    const [row, col] = queue.popFront()!;\n    for (const [nr, nc] of neighbors(row, col, rows, cols)) {\n        if (rooms[nr][nc] !== -1 && rooms[nr][nc] !== 0) {\n            rooms[nr][nc] = (rooms[row][col] + 1);\n            queue.pushBack([nr, nc]);\n        }\n    }\n}\nreturn rooms;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":5,"8":6,"11":11,"12":12,"13":13,"14":14,"15":15,"16":18,"18":20,"19":21,"20":22,"21":23,"22":24,"23":25,"24":29},"statementBundles":{"8":{"startLine":6,"endLine":10},"15":{"startLine":15,"endLine":17},"16":{"startLine":18,"endLine":19},"23":{"startLine":25,"endLine":28}}},"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, 0)), new ArrayList<>(List.of(-1, 0)), new ArrayList<>(List.of(0, 1)), new ArrayList<>(List.of(0, -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 = rooms.size();\nint cols = rooms.get(0).size();\nDeque<List<Integer>> queue = new ArrayDeque<>();\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (rooms.get(r).get(c) == 0) {\n            queue.addLast(new ArrayList<>(List.of(r, c)));\n        }\n    }\n}\nwhile (!queue.isEmpty()) {\n    List<Integer> item = queue.pollFirst();\n    int row = item.get(0);\n    int col = item.get(1);\n    for (List<Integer> itemEntry : neighbors(row, col, rows, cols)) {\n        int nr = itemEntry.get(0);\n        int nc = itemEntry.get(1);\n        if ((rooms.get(nr).get(nc) != -1 && rooms.get(nr).get(nc) != 0)) {\n            rooms.get(nr).set(nc, (rooms.get(row).get(col) + 1));\n            queue.addLast(new ArrayList<>(List.of(nr, nc)));\n        }\n    }\n}\nreturn rooms;","lineMap":{"3":15,"4":17,"5":18,"6":19,"7":20,"8":21,"11":2,"12":3,"13":6,"14":8,"15":9,"16":12,"18":25,"19":26,"20":29,"21":32,"22":33,"23":34,"24":38},"statementBundles":{"3":{"startLine":15,"endLine":16},"8":{"startLine":21,"endLine":24},"12":{"startLine":3,"endLine":5},"13":{"startLine":6,"endLine":7},"15":{"startLine":9,"endLine":11},"16":{"startLine":12,"endLine":13},"19":{"startLine":26,"endLine":28},"20":{"startLine":29,"endLine":31},"23":{"startLine":34,"endLine":37}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"var (rows, cols) = (rooms.Count, rooms[0].Count);\nQueue<List<int>> queue = new();\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (rooms[r][c] == 0) {\n            queue.Enqueue(new List<int> { r, c });\n        }\n    }\n}\nList<(int, int)> Neighbors(int r, int c, int rows, int cols) {\n    List<(int, int)> result = new();\n    foreach (var item in new List<List<int>> { new List<int> { 1, 0 }, new List<int> { -1, 0 }, new List<int> { 0, 1 }, new List<int> { 0, -1 } }) {\n        int dr = item[0];\n        int dc = item[1];\n        var (nr, nc) = (r + dr, c + dc);\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            result.Add((nr, nc));\n        }\n    }\n    return result;\n    return null;\n}\nwhile (queue.Count > 0) {\n    List<int> item = queue.Dequeue();\n    int row = item[0];\n    int col = item[1];\n    foreach (var (nr, nc) in Neighbors(row, col, rows, cols)) {\n        if (rooms[nr][nc] != -1 && rooms[nr][nc] != 0) {\n            rooms[nr][nc] = rooms[row][col] + 1;\n            queue.Enqueue(new List<int> { nr, nc });\n        }\n    }\n}\nreturn rooms;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":5,"8":6,"11":11,"12":12,"13":15,"14":16,"15":17,"16":20,"18":23,"19":24,"20":27,"21":28,"22":29,"23":30,"24":34},"statementBundles":{"8":{"startLine":6,"endLine":10},"12":{"startLine":12,"endLine":14},"15":{"startLine":17,"endLine":19},"16":{"startLine":20,"endLine":22},"19":{"startLine":24,"endLine":26},"23":{"startLine":30,"endLine":33}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int rows = rooms.size();\nint cols = rooms[0].size();\nvector<pair<int, int>> queue;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (rooms[r][c] == 0) {\n            queue.push_back(pair<int, int>{r, c});\n        }\n    }\n}\nauto neighbors = [&]( int r, int c, int rows, int cols ) -> vector<pair<int, int>> {\n    vector<pair<int, int>> result;\n    for (vector<int> item : vector<vector<int>>{{1, 0}, {-1, 0}, {0, 1}, {0, -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(pair<int, int>{nr, nc});\n        }\n    }\n    return result;\n};\nwhile (!queue.empty()) {\n    auto popped_item = queue.front(); queue.erase(queue.begin());\n    auto [row, col] = popped_item;\n    for (auto [nr, nc] : neighbors(row, col, rows, cols)) {\n        if ((rooms[nr][nc] != -1 && rooms[nr][nc] != 0)) {\n            rooms[nr][nc] = (rooms[row][col] + 1);\n            queue.push_back(pair<int, int>{nr, nc});\n        }\n    }\n}\nreturn rooms;","lineMap":{"3":1,"4":3,"5":4,"6":5,"7":6,"8":7,"11":12,"12":13,"13":16,"14":18,"15":19,"16":22,"18":24,"19":25,"20":27,"21":28,"22":29,"23":30,"24":34},"statementBundles":{"3":{"startLine":1,"endLine":2},"8":{"startLine":7,"endLine":11},"12":{"startLine":13,"endLine":15},"13":{"startLine":16,"endLine":17},"15":{"startLine":19,"endLine":21},"16":{"startLine":22,"endLine":23},"19":{"startLine":25,"endLine":26},"23":{"startLine":30,"endLine":33}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Spreading rings from every gate filled the sample grid, each room claimed once by its nearest gate and the queue draining when no empty neighbour remained.","Two grids deserve a look before you code: one where walls seal a room off from every gate, and one with no gates at all to start the spread."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"grid":[[0,1,2,1],[1,-1,-1,0]],"labels":{"grid":"rooms"}}}]}},{"id":"walled-off-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What happens to a room sealed off by walls?","summary":"In [[INF,-1,0]] the room at (0,0) is cut off from the gate by a wall.","workspacePanel":"visualizer","options":[{"id":"stays-inf","label":"It stays INF, because no ring ever reaches it","rationale":"A walled-off room is never an empty neighbour of any spreading cell, so it is never written and never enqueued. It keeps its starting INF.","isCorrect":true},{"id":"zero","label":"It becomes 0 like a gate","rationale":"Only gates start at 0. An unreachable room is never filled at all, so it keeps INF.","isCorrect":false},{"id":"wall-dist","label":"It takes the distance to the nearest wall","rationale":"Distance is measured to gates, not walls. A room no gate can reach simply stays INF.","isCorrect":false}],"answer":"It stays INF. The wall keeps it out of every ring, so it is never written and the starting INF remains.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"walled-state","state":{"grid":[[2147483647,-1,0]],"labels":{"grid":"rooms"}}}]}},{"id":"no-gates-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if the grid has no gates at all?","summary":"The grid holds only empty rooms, with no gate anywhere.","workspacePanel":"visualizer","options":[{"id":"unchanged","label":"Every room stays INF, since the queue starts empty","rationale":"The seed scan adds only gates, so with no gate the queue is empty and the spread never runs. Every room keeps INF and the grid returns unchanged.","isCorrect":true},{"id":"all-zero","label":"Every room becomes 0","rationale":"A room only becomes 0 if it is a gate. With no gates, no room is ever written, so all stay INF.","isCorrect":false},{"id":"error","label":"The empty queue is an error to guard against","rationale":"An empty queue is not an error: the loop simply never runs and the unchanged grid is returned.","isCorrect":false}],"answer":"Every room stays INF. No gate means the queue is seeded empty, the spread never starts, and the grid comes back unchanged.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-gates-state","state":{"grid":[[2147483647,2147483647],[2147483647,2147483647]],"labels":{"grid":"rooms"}}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Fill a room only while it still holds INF, so the first ring to reach it wins.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[0,2147483647,2147483647,2147483647],[2147483647,-1,-1,0]],"frontier":[[0,0],[1,3]],"labels":{"grid":"rooms"}}}]},"body":["Seed the queue with every gate. Take the front cell, and for each neighbour that is still an empty room, write the current distance plus one and add it to the queue. Skip rooms already filled so each keeps its nearest-gate distance. When the queue empties, return the grid, with any walled-off room still INF."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the distance wavefront","eyebrow":"Code the rule","summary":"Seed all gates, process BFS layers from the queue, fill only INF rooms, and return the mutated grid.","workspacePanel":"code","checkpoints":[{"id":"init-frontier","title":"Seed all gates","description":"Scan the grid and enqueue every gate as an initial BFS source.","commonMistakes":["Starting from only the first gate","Starting BFS from empty rooms"],"hint":"All gates should enter the queue before expansion starts.","semanticSpec":{"intent":"Initialize the BFS frontier and auxiliary state.","doneWhen":"The queue is initialized from the grid before traversal.","shouldFailWhen":"No frontier is created before the BFS loop.","roles":["frontier queue","gate cells"],"mustProve":["BFS frontier initialization exists."],"mustNotAccept":["A scan with no queued frontier."],"equivalentVariants":["Use a list with a head index or a deque/queue structure."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"initializes_frontier_and_aux_state","scope":"init-queue","readMode":"bfs-queue-value-query-v1"}]}},{"id":"bfs-loop","title":"Process the frontier","description":"Loop while queued cells remain and pop the next room to expand.","commonMistakes":["Using one pass over the grid instead of BFS","Never advancing the queue head"],"hint":"The loop should continue until every reachable room has been claimed.","semanticSpec":{"intent":"Drive the BFS traversal loop.","doneWhen":"The code loops while the frontier is non-empty.","shouldFailWhen":"Queued cells are never processed.","roles":["frontier queue","current cell"],"mustProve":["The frontier loop is driven by queued cells."],"mustNotAccept":["A fixed number of expansion passes."],"equivalentVariants":["Use `while queue`, `while head < len(queue)`, or equivalent."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"loops_while_frontier_non_empty","scope":"bfs-loop","readMode":"bfs-queue-value-query-v1"}]}},{"id":"expand-neighbors","title":"Check neighboring rooms","description":"For each current cell, inspect the four adjacent cells and keep only in-bounds empty rooms.","commonMistakes":["Skipping one direction","Walking through walls"],"hint":"Only `INF` cells should be filled and enqueued.","semanticSpec":{"intent":"Expand valid frontier neighbors.","doneWhen":"The BFS loop checks adjacent grid positions with bounds and room-state guards.","shouldFailWhen":"Neighbors are not inspected from each popped cell.","roles":["current cell","neighbor cell","grid bounds"],"mustProve":["Neighbors are expanded from the BFS frontier."],"mustNotAccept":["Updating arbitrary cells without adjacency."],"equivalentVariants":["Use a direction array or explicit four-neighbor checks."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"check-neighbors","readMode":"bfs-queue-value-query-v1"}]}},{"id":"enqueue-neighbors","title":"Fill and enqueue each reached room until the grid is complete","description":"Assign each newly reached room `current + 1` and enqueue it so it spreads the next ring; when the queue drains, every reachable room holds its final distance.","commonMistakes":["Enqueuing without marking the room","Writing a constant distance"],"hint":"The current cell already stores the shortest distance to a gate; each written neighbor continues the BFS frontier.","semanticSpec":{"intent":"Enqueue derived frontier cells after mutation.","doneWhen":"A newly filled room is added to the frontier so its own ring spreads later.","shouldFailWhen":"Rooms are filled but not enqueued for propagation.","roles":["distance value","neighbor payload"],"mustProve":["Derived neighbor state is enqueued."],"mustNotAccept":["Only modifying the first layer."],"equivalentVariants":["Store distance in the grid or in a paired distance payload."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"enqueues_derived_frontier_state_and_returns_mutated_input","scope":"rot-fresh","readMode":"bfs-queue-value-query-v1","expected":{"param":"rooms"}}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Spread distance from every gate at once; the first ring to reach a room carries its nearest-gate distance.","workspacePanel":"code","body":["This is a multi-source breadth-first fill: every gate spreads outward together, one ring of distance per step, so rooms are claimed in increasing-distance order.","Seed the queue with all gates, fill each still-empty neighbour with distance plus one, and stop touching a room once it is filled."],"takeaways":[{"title":"All gates start together","body":"Seeding every gate before the first ring is what makes the first arrival at any room come from its nearest gate."},{"title":"First write wins","body":"Rings arrive nearest-first, so filling a room only while it still holds INF keeps every distance at the shortest, with no comparison needed."},{"title":"Unreached stays INF","body":"A room walls cut off from every gate is never enqueued, so INF is the correct final value for that room."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
