{"id":"shortest-bridge","title":"Shortest Bridge","difficulty":"medium","patterns":["graph-bfs","graph-dfs"],"primaryConcept":"graph-grid-fill","concepts":["graph-grid-fill","graph-components"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"grid","sizeMetric":"matrix-cells","constraints":["binary-int","exactly-two-islands","bridge-distance"],"sizes":[9,25,64,144]},"description":"You are given an `n x n` binary grid containing exactly two islands. An island is a 4-directionally connected group of `1` cells.\n\nYou may change `0` cells to `1`. Return the smallest number of `0` cells that must be changed to connect the two islands.","examples":[{"input":"grid = [[0,1],[1,0]]","output":"1","explanation":"Flip either water cell to connect the two diagonal islands."},{"input":"grid = [[0,1,0],[0,0,0],[0,0,1]]","output":"2","explanation":"Two water cells are needed to bridge the top island to the bottom-right island."},{"input":"grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]","output":"1","explanation":"The center island is one water flip away from the surrounding island."}],"constraints":[{"id":"n-len-grid","text":"n == len(grid)"},{"id":"n-len-grid-i","text":"n == len(grid[i])"},{"id":"2-n-100","text":"2 <= n <= 100"},{"id":"grid-i-j-is-0-or-1","text":"grid[i][j] is 0 or 1","check":{"kind":"domain","target":"grid","selector":"nestedArrayItems","allowed":[0,1],"rectangular":true}},{"id":"grid-contains-exactly-two-islands","text":"grid contains exactly two islands"}],"starterCode":"class Solution:\n    def shortestBridge(self, grid: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"shortestBridge","testCases":[{"id":"1","input":{"grid":[[0,1],[1,0]]},"expected":1,"description":"Two diagonal single-cell islands."},{"id":"2","input":{"grid":[[0,1,0],[0,0,0],[0,0,1]]},"expected":2,"description":"Single-cell islands separated by two water cells."},{"id":"3","input":{"grid":[[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]},"expected":1,"description":"Center island is inside a ring island."},{"id":"4","input":{"grid":[[1,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,1]]},"expected":3,"description":"Two larger islands separated by a wider channel."},{"id":"h1","input":{"grid":[[1,0,1],[0,0,0],[0,0,0]]},"expected":1,"description":"Same-row islands separated by one water cell."},{"id":"h2","input":{"grid":[[1,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1]]},"expected":7,"description":"Opposite corners."},{"id":"h3","input":{"grid":[[1,1,1,0,0],[1,0,1,0,0],[1,1,1,0,1],[0,0,0,0,1],[0,0,0,1,1]]},"expected":1,"description":"Large island one flip away from a second island."},{"id":"h4","input":{"grid":[[1,0,0],[0,0,0],[0,0,1]]},"description":"Two single-cell islands sit in opposite corners.","expected":3},{"id":"h5","input":{"grid":[[1,1,0],[0,0,0],[0,1,1]]},"description":"A diagonal approach reaches the second island quickly.","expected":1},{"id":"h6","input":{"grid":[[1,0,0,0],[1,0,0,0],[1,0,0,1],[0,0,0,1]]},"description":"Two vertical islands separated by a wide water channel.","expected":2},{"id":"topup-column-separated-islands","input":{"grid":[[1,1,0,0,0],[1,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,1]]},"expected":5,"description":"Diagonal-corner islands require crossing the center water layer."},{"id":"topup-adjacent-large-islands","input":{"grid":[[1,1,0,0],[1,1,0,1],[0,0,0,1],[0,0,1,1]]},"expected":1,"description":"Two multi-cell islands are separated by a narrow channel."}],"hints":[{"level":1,"content":"First identify one whole island. Then expand outward from all of its cells together.","revealPattern":false},{"level":2,"content":"Use DFS to mark the first island and seed a BFS queue with its cells.","revealPattern":true},{"level":3,"content":"BFS layers count how many water cells have been flipped. The first time BFS touches the second island, `return` that layer distance.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach gives the minimum flips?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"dfs-seed-bfs","name":"DFS-seeded BFS","summary":"Mark the first island, enqueue all its cells at distance 0, and BFS through water until reaching the second island.","decisionReason":"DFS marks every cell of one island and seeds BFS from all of them at distance 0. The first time BFS touches the second island, its layer count is the smallest number of water cells flipped.","complexity":{"time":"O(n^2)","space":"O(n^2)"},"tradeoffs":["Runs in O(n^2) time and uses O(n^2) space."],"isOptimal":true},{"id":"try-every-pair","name":"Compare every island-cell pair","summary":"List cells from both islands and compute Manhattan distances between all pairs.","decisionReason":"Listing both islands and comparing every pair is correct, but it can multiply to O(n^4) when both islands cover large parts of the grid. BFS expands water layers once, so it reaches the closest cell without pairwise distances.","complexity":{"time":"O(n^4)","space":"O(n^2)"},"tradeoffs":["Runs in O(n^4) time and uses O(n^2) space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"find-first-island","title":"Find a first island cell","description":"Scan the grid until you find a land cell that can seed the first island traversal.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops","readMode":"grid-enumeration-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"gates_fresh_cell_before_component_entry","scope":"check-land","readMode":"grid-recursive-search-value-query-v1"}]}]},"commonMistakes":["Starting from water","Continuing to mark both islands before BFS"],"hint":"The first `1` you find can seed the first island; stop looking once that island has been marked.","semanticSpec":{"intent":"Locate a land cell and gate the first component traversal on that land check.","doneWhen":"The grid scan finds a `1` and uses it as the DFS entry point.","mustProve":["The grid is scanned by row and column.","DFS starts only after checking that the current cell is land."],"mustNotAccept":["DFS from every cell without a land gate."],"proofSnippets":[{"id":"py-shortest-bridge-find-first-island","language":"python","code":"def shortestBridge(grid: list[list[int]]) -> int:\n    for r in range(len(grid)):\n        for c in range(len(grid[0])):\n            if grid[r][c] == 1:\n                return 0"}],"roles":["grid scan","first island cell"]}},{"id":"mark-first-island","title":"Mark the first island","description":"Use DFS from the first land cell to mark every cell in that island and avoid revisiting it.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_recursive_cell_exploration","scope":"call-dfs","readMode":"grid-recursive-search-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"guards_boundary_before_exploration","scope":"dfs-base-case","readMode":"grid-recursive-search-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"explores_grid_neighbors","scope":"explore-neighbors","readMode":"grid-recursive-search-value-query-v1"}]}]},"commonMistakes":["Only marking the starting cell","Letting DFS cross water into the other island"],"hint":"DFS should stop on water or marked cells and recurse only through 4-directional land.","semanticSpec":{"intent":"Consume the first connected component before BFS begins.","doneWhen":"A recursive grid helper marks the whole first island and stops at water, bounds, or already-marked cells.","mustProve":["The recursive helper has boundary/cell guards.","The helper explores neighboring grid cells."],"mustNotAccept":["A helper that cannot reach all cells of the first island."],"roles":["DFS helper","first island","marked cells"]}},{"id":"seed-bfs-frontier","title":"Seed BFS from the marked island","description":"Add first-island cells to a queue with distance 0 so the bridge expands from the entire island at once.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"initializes_frontier_and_aux_state","scope":"init-queue","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Enqueueing only one island cell","Starting distance at 1"],"hint":"Every cell of the first island can be a distance-0 starting point.","semanticSpec":{"intent":"Initialize the BFS frontier from the first island.","doneWhen":"The queue is initialized and populated with island cells carrying a distance state.","mustProve":["A BFS frontier is initialized before the traversal loop."],"mustNotAccept":["A BFS loop with no seeded frontier."],"roles":["frontier queue","distance"]}},{"id":"bfs-loop","title":"Expand BFS layers","description":"Process queued cells in FIFO order so each water layer represents one additional flip.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"loops_while_frontier_non_empty","scope":"bfs-loop","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Using DFS for the expansion","Losing the distance value carried by each queued cell"],"hint":"The first time BFS reaches the second island is the shortest bridge.","semanticSpec":{"intent":"Drive the bridge expansion with FIFO BFS.","doneWhen":"The queue is repeatedly dequeued until a terminal condition is reached.","mustProve":["A frontier loop consumes queued states in BFS order."],"mustNotAccept":["A stack-like expansion."],"roles":["frontier queue","distance layer"]}},{"id":"check-neighbors","title":"Check four neighboring cells","description":"From each BFS cell, inspect the four cardinal neighbors and skip invalid or already-marked cells.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"check-neighbors","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Including diagonals","Forgetting bounds checks","Revisiting the first island"],"hint":"Only unmarked in-bounds neighbors are candidates for expansion or termination.","semanticSpec":{"intent":"Evaluate the four orthogonal expansion choices from each frontier cell.","doneWhen":"BFS checks up, down, left, and right with bounds and visited guards.","mustProve":["The frontier expansion iterates over neighboring grid coordinates."],"mustNotAccept":["Diagonal expansion."],"roles":["neighbor coordinates","visited guard"]}},{"id":"enqueue-water","title":"Enqueue water as the next layer","description":"When BFS finds water, mark it and enqueue it with distance + 1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"enqueues_derived_frontier_state","scope":"rot-fresh","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Not marking water before enqueueing it","Reusing the same distance instead of distance + 1"],"hint":"A water cell added to the queue represents one more flip than the current cell.","semanticSpec":{"intent":"Schedule newly reached water cells as the next bridge layer.","doneWhen":"Each accepted water neighbor is marked and enqueued with incremented distance.","mustProve":["A derived neighbor state is enqueued from the current frontier state."],"mustNotAccept":["Constant or stale enqueue payloads."],"roles":["water neighbor","next distance"]}},{"id":"return-distance","title":"Return when the second island is reached","description":"The first second-island cell reached by BFS gives the shortest bridge length.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"returns_terminal_result_during_frontier_expansion","scope":"return-result","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Returning distance + 1 when the neighbor is already land","Continuing BFS after reaching the second island"],"hint":"When a frontier cell touches original land from the second island, the current distance is the number of water cells flipped.","semanticSpec":{"intent":"Stop at the first contact with the second island and return the BFS distance.","doneWhen":"A terminal return occurs during frontier expansion when an unmarked land neighbor is found.","mustProve":["The BFS expansion returns its distance result when the target island is reached."],"mustNotAccept":["Returning after all layers without detecting second-island contact."],"roles":["second island","BFS distance","terminal return"]}}],"slides":[{"id":"read-the-signal","chapter":"The two islands","kind":"info","eyebrow":"Read the problem","title":"Connect the two islands with the fewest flips","workspacePanel":"problem","body":["You get an n by n grid containing exactly two islands, where 0 is water and 1 is land. You may flip water cells to land; return the smallest number of flips that joins the islands through up, down, left, or right steps.","The shortest bridge is the first point where an outward expansion from one entire island reaches the other. Starting from one land cell would measure from the wrong boundary."]},{"id":"what-a-bridge-is","chapter":"The two islands","kind":"info","eyebrow":"See the shape","title":"A bridge is a path of flipped water","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-islands","state":{"grid":[[0,1,0],[0,0,0],[0,0,1]],"frontier":[[0,1],[2,2]]}}]},"body":["Here the top island is the single cell (0,1) and the second island is the single cell (2,2). The badged cells are the two pieces of land.","A bridge is a chain of water cells you flip so that land becomes one connected group. Its length is how many water cells you flipped.","So the question is really a shortest-path question: across the water between the two islands, what is the fewest cells the bridge has to cross?"]},{"id":"all-pairs","chapter":"The obvious way","kind":"code-trace","source":"brute-force","eyebrow":"Start naive","title":"Measure every pair of land cells","summary":"A direct plan lists the cells of each island, then measures straight-line gaps between the two lists. Watch how many pairings it walks through.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def minimumGap(first: list[list[int]], second: list[list[int]]) -> int:\n    best = 1000000000\n    for r1, c1 in first:\n        for r2, c2 in second:\n            gap = abs(r1 - r2) + abs(c1 - c2) - 1\n            best = min(best, gap)\n    return best","steps":[{"id":"p1","title":"Pair a first-island cell with a second-island cell","codeLine":5,"summary":"(1,0) against (3,3): rows differ by 2, columns by 3, so the straight-line gap of water is 2 + 3 - 1 = 4.","state":{"grid":[[1,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,1]],"r":1,"c":0,"filled":[[3,3]],"changed":[[3,3]]}},{"id":"p2","title":"Same first cell, next second-island cell","codeLine":5,"summary":"(1,0) against (3,2): rows differ by 2, columns by 2, giving a gap of 2 + 2 - 1 = 3. The inner loop reruns for every cell of the second island.","state":{"grid":[[1,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,1]],"r":1,"c":0,"filled":[[3,2]],"changed":[[3,2]]}},{"id":"p3","title":"Advance the first island cell and pair again","codeLine":5,"summary":"Now (0,1) against (2,3): rows differ by 2, columns by 2, another gap of 3. Every first-island cell restarts the whole inner loop over the second island.","state":{"grid":[[1,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,1]],"r":0,"c":1,"filled":[[2,3]],"changed":[[2,3]]}},{"id":"p4","title":"The smallest gap wins","codeLine":7,"summary":"The best gap found across all pairs is 3, so the answer is 3. Every first-island cell had to be measured against every second-island cell to be sure none was closer.","state":{"grid":[[1,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,1]],"filled":[[1,1],[2,1],[2,2]],"changed":[[1,1],[2,1],[2,2]]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let best = 1000000000;\nfor (const [r1, c1] of first) {\n    for (const [r2, c2] of second) {\n        const gap = (Math.abs((r1 - r2)) + Math.abs((c1 - c2))) - 1;\n        best = Math.min(best, gap);\n    }\n}\nreturn best;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":8},"statementBundles":{"6":{"startLine":5,"endLine":7}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let best = 1000000000;\nfor (const [r1, c1] of first) {\n    for (const [r2, c2] of second) {\n        const gap = (Math.abs((r1 - r2)) + Math.abs((c1 - c2))) - 1;\n        best = Math.min(best, gap);\n    }\n}\nreturn best;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":8},"statementBundles":{"6":{"startLine":5,"endLine":7}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int best = 1000000000;\nfor (List<Integer> item : first) {\n    int r1 = item.get(0);\n    int c1 = item.get(1);\n    for (List<Integer> itemEntry : second) {\n        int r2 = itemEntry.get(0);\n        int c2 = itemEntry.get(1);\n        int gap = (Math.abs(r1 - r2) + Math.abs(c1 - c2)) - 1;\n        best = Math.min(best, gap);\n    }\n}\nreturn best;","lineMap":{"2":1,"3":2,"4":5,"5":8,"6":9,"7":12},"statementBundles":{"3":{"startLine":2,"endLine":4},"4":{"startLine":5,"endLine":7},"6":{"startLine":9,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int best = 1000000000;\nforeach (var item in first) {\n    int r1 = item[0];\n    int c1 = item[1];\n    foreach (var item1 in second) {\n        int r2 = item1[0];\n        int c2 = item1[1];\n        int gap = Math.Abs(r1 - r2) + Math.Abs(c1 - c2) - 1;\n        best = Math.Min(best, gap);\n    }\n}\nreturn best;","lineMap":{"2":1,"3":2,"4":5,"5":8,"6":9,"7":12},"statementBundles":{"3":{"startLine":2,"endLine":4},"4":{"startLine":5,"endLine":7},"6":{"startLine":9,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int best = 1000000000;\nfor (vector<int> item : first) {\n    int r1 = item[0];\n    int c1 = item[1];\n    for (vector<int> item : second) {\n        int r2 = item[0];\n        int c2 = item[1];\n        int gap = (abs((r1 - r2)) + abs((c1 - c2))) - 1;\n        best = min(best, gap);\n    }\n}\nreturn best;","lineMap":{"2":1,"3":2,"4":5,"5":8,"6":9,"7":12},"statementBundles":{"3":{"startLine":2,"endLine":4},"4":{"startLine":5,"endLine":7},"6":{"startLine":9,"endLine":11}}}}}},{"id":"all-pairs-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Count the cost","title":"How much work does measuring every pair cost?","summary":"One approach stores both land groups before measuring distances between them.","workspacePanel":"visualizer","visualTrace":{"contract":"visual-trace-v1","steps":[{"id":"every-pair","title":"Every first-island cell crossed with every second-island cell","summary":"All three first-island cells (shaded) are measured against all three second-island cells (badged), so the loop body runs for every pairing. When each island can fill a large slice of the grid, that product of cells is what makes the work pile up.","state":{"labels":{"grid":"grid"},"grid":[[1,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,1]],"filled":[[0,0],[0,1],[1,0]],"changed":[],"frontier":[[2,3],[3,2],[3,3]]}}]},"options":[{"id":"pairs","label":"Every first-island cell against every second-island cell, so the cells of one island times the cells of the other","rationale":"Both islands can grow to a large fraction of the grid's n squared cells, so pairing them all is roughly n squared times n squared work, about n to the fourth.","isCorrect":true},{"id":"linear","label":"One pass over the grid, about n squared total","rationale":"A single scan only labels the islands. Finding the closest pair still needs to compare cells across the two islands, which a single pass does not do.","isCorrect":false},{"id":"edges","label":"Roughly the number of cells on each island's edge","rationale":"The straight-line measure has no edge-only filter, so interior cells get paired with the other island too.","isCorrect":false}],"answer":"It pairs every first-island cell with every second-island cell, and each island can be a large slice of the n squared grid, so the work climbs toward n to the fourth. That all-pairs cost is what we want to beat: a single coloring sweep plus one outward ripple settles the same answer in n squared work."},{"id":"seed-whole-island","chapter":"The idea","kind":"case-probe","eyebrow":"Find the start","title":"To find the nearest reach of the second island, where should the water search start?","summary":"The first island has already been found and colored. Now the bridge has to grow out from it.","workspacePanel":"visualizer","options":[{"id":"whole-island","label":"From every cell of the first island at once, all seeded as the starting layer","rationale":"The bridge can leave the island from any of its cells, so the nearest crossing might start anywhere along its shore. Seeding all of them together lets a single outward search find the closest reach to the second island.","isCorrect":true},{"id":"one-cell","label":"From the single cell where the scan first found the island","rationale":"The closest crossing may leave from a different part of the shore than where the scan happened to start, so searching from one cell can miss the shortest bridge.","isCorrect":false},{"id":"nearest-guess","label":"From the island cell that looks closest to the second island","rationale":"Guessing the closest cell needs the answer you are trying to find. Seeding the whole shore at once lets the search settle which crossing is shortest on its own.","isCorrect":false}],"answer":"From the entire first island at once. Seed every one of its cells as the starting layer, so the water search grows outward from the whole shore and finds the nearest reach of the second island.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seed-state","state":{"grid":[[2,2,0,0],[2,0,0,0],[0,0,0,1],[0,0,1,1]],"frontier":[[0,0],[0,1],[1,0]]}}]}},{"id":"layer-is-flips","chapter":"The idea","kind":"case-probe","eyebrow":"Count the distance","title":"As the search grows outward, what does one more layer count?","summary":"The frontier moves from its current cells to adjacent grid cells in layers.","workspacePanel":"visualizer","options":[{"id":"one-flip","label":"One more water cell flipped on the way across","rationale":"Each ring steps exactly one cell further from the island, and that cell is a flip the bridge would make. So the ring number is the count of water cells flipped to reach it.","isCorrect":true},{"id":"one-cell-visited","label":"One more cell looked at, island land included","rationale":"The search only steps onto water it has not flipped yet, not back over island land. The ring counts flips made, not every cell glanced at.","isCorrect":false},{"id":"one-island","label":"One more island reached","rationale":"There are only two islands. The rings count distance across the water between them, not islands.","isCorrect":false}],"answer":"One more flipped water cell. Each ring is one cell further from the first island, so when a ring first touches the second island, its number is the bridge length.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"layer-state","state":{"grid":[[2,2,0,0],[2,0,0,0],[0,0,0,1],[0,0,1,1]],"frontier":[[0,2],[1,1],[2,0]]}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which way reaches the second island fastest?","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"Which way reaches the second island fastest?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"dfs-seed-bfs","name":"Color one island, then ripple out","summary":"Use a depth-first sweep to color the whole first island, seed every colored cell as the search's first layer, and grow rings of water outward until one touches the second island.","decisionReason":"Coloring the island is one grid sweep, and the outward ripple touches each cell once, so the whole search settles the shortest bridge in a single n squared pass.","complexity":{"time":"O(n^2)","space":"O(n^2)"},"tradeoffs":["Each cell is colored or rippled once, so the work is proportional to the grid's n squared cells."],"isOptimal":true},{"id":"try-every-pair","name":"Measure every pair of land cells","summary":"Label the two islands, then measure the straight-line gap between every first-island cell and every second-island cell, keeping the smallest.","decisionReason":"This finds the right minimum, but pairing every cell of one island with every cell of the other is about n to the fourth work, far above the n squared a single coloring sweep plus outward ripple needs.","complexity":{"time":"O(n^4)","space":"O(n^2)"},"tradeoffs":["Correct, but every island-cell pair is measured, so the cost climbs to n to the fourth."],"isOptimal":false}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"grid":[[2,2,0,0],[2,0,0,0],[0,0,0,1],[0,0,1,1]],"frontier":[[0,0],[0,1],[1,0]]}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Color the island, then grow rings","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"grid":[[0,2,0],[0,0,0],[0,0,1]],"frontier":[[0,1]]}}]},"body":["The first island, the single cell (0,1), is now colored and seeded as the starting layer at distance 0. The second island is the cell (2,2).","Each step takes the current ring, steps onto every fresh water neighbour, and forms the next ring one distance further out.","The moment a ring is about to step onto the second island's original land, the distance it carries is the bridge length."]},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","title":"Grow the bridge ring by ring","eyebrow":"Trace the search","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ring-one","state":{"grid":[[2,2,2],[0,2,0],[0,0,1]],"frontier":[[0,0],[0,2],[1,1]]}},{"id":"ring-two","state":{"grid":[[2,2,2],[2,2,2],[0,2,1]],"frontier":[[1,0],[1,2],[2,1]]}},{"id":"touch","state":{"grid":[[2,2,2],[2,2,2],[0,2,1]],"r":2,"c":2,"frontier":[[2,1]]}}]},"beats":[{"id":"ring-one","title":"Ring 1 grows from the island. Which cells does it flip?","summary":"The starting layer holds just (0,1) at distance 0.","prompt":"The seeded cell at (0,1) checks its four directions.","options":[{"id":"three-neighbors","label":"Its three water neighbours, each now at distance 1","rationale":"From (0,1) the search steps onto (0,0), (0,2), and (1,1). Each is one flip out, so they form ring 1 at distance 1.","isCorrect":true},{"id":"diagonal-too","label":"Its neighbours including the diagonal cells","rationale":"The search only steps up, down, left, and right, never diagonally, so the diagonal water cells are not part of ring 1.","isCorrect":false},{"id":"second-island","label":"Straight across to the second island","rationale":"The second island at (2,2) is two flips away. The search can only reach the cells directly beside the island first.","isCorrect":false}],"answer":"The three water neighbours (0,0), (0,2), and (1,1) flip, forming ring 1 at distance 1."},{"id":"ring-two","title":"Ring 2 grows from ring 1. How far out is it now?","summary":"Distance 1 contains (0,0), (0,2), and (1,1).","prompt":"Expand from that frontier.","options":[{"id":"distance-two","label":"The next water cells, at distance 2","rationale":"Ring 2 is one step past ring 1, so its cells carry distance 2: two water flips from the island. (2,1) is one of them, and it sits right beside the second island.","isCorrect":true},{"id":"still-one","label":"Still distance 1, the same minute","rationale":"Ring 1 already used distance 1. Stepping one cell further must add a flip, so the new cells are at distance 2.","isCorrect":false},{"id":"done-now","label":"Distance 2, and we return 3 because the island is one more step","rationale":"Reaching the island is not another flip. The bridge is the water flipped so far, which the next beat settles.","isCorrect":false}],"answer":"The new cells are at distance 2, two flips from the island. One of them, (2,1), sits directly beside the second island."},{"id":"touch","title":"A distance-2 cell sits next to original land. What is the bridge length?","summary":"The cell (2,1), carrying distance 2, looks at its neighbour (2,2), which is the second island's original land.","prompt":"The search has reached the far island.","options":[{"id":"two","label":"2","rationale":"The cell making contact carries distance 2, meaning two water cells were flipped to get there. Touching the island adds no flip, so the bridge is 2.","isCorrect":true},{"id":"three","label":"3","rationale":"3 would count the island cell itself as a flip. The island is already land, so only the two water cells crossed count.","isCorrect":false},{"id":"one","label":"1","rationale":"1 is the distance of the previous ring. Contact happens from a distance-2 cell, so the bridge is 2.","isCorrect":false}],"answer":"2. The contacting cell carries distance 2, the two water cells flipped to reach the second island, and the island itself is not a flip."}]},{"id":"off-by-one-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"When a ring touches the far island, should it return one more?","summary":"A mistaken version returns distance + 1 when the search touches the far island. Watch where its count diverges from the bridge you actually flip.","workspacePanel":"trace","pitfall":"The code below grows rings exactly like the search you are building, carrying a distance with each cell, but when a neighbour turns out to be the second island it returns distance + 1 instead of distance.","whyItMatters":"The cell making contact already holds the number of water cells flipped to reach it, and the second island's land needs no flip. Returning distance + 1 counts the island cell as a flip. The fix is to return distance the moment a neighbour is original land.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def expandBridge(grid: list[list[int]], queue: list[list[int]]) -> int:\n    rows = len(grid)\n    cols = len(grid[0])\n    directions: list[list[int]] = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n    head = 0\n    while head < len(queue):\n        r, c, distance = queue[head]\n        head += 1\n        for dr, dc in directions:\n            nr = r + dr\n            nc = c + dc\n            if 0 <= nr < rows and 0 <= nc < cols:\n                if grid[nr][nc] == 1:\n                    return distance + 1\n                if grid[nr][nc] == 0:\n                    grid[nr][nc] = 2\n                    queue.append([nr, nc, distance + 1])\n    return -1","steps":[{"id":"grow-rings","title":"The rings grow across the water","codeLine":17,"summary":"grid = [[0,1,0],[0,0,0],[0,0,1]]. The first island (0,1) is seeded at distance 0, and two rings of water flips grow outward, reaching distance 2 beside the second island.","state":{"grid":[[2,2,2],[2,2,2],[0,2,1]],"frontier":[[2,1]]}},{"id":"contact","title":"A distance-2 cell touches the island","codeLine":14,"summary":"The cell (2,1), carrying distance 2, looks at (2,2) and finds original land. Exactly two water cells, (1,1) and (2,1), were flipped to get here.","state":{"grid":[[2,2,2],[2,2,2],[0,2,1]],"r":2,"c":2,"frontier":[[2,1]]}},{"id":"wrong-return","title":"It returns one too many","codeLine":14,"summary":"Because (2,2) is original land, the code returns distance + 1 right away, handing back 3 without ever flipping or marking that cell. Only 2 water cells were flipped, so the step onto land was counted as a flip it never made and the real answer of 2 is lost.","state":{"grid":[[2,2,2],[2,2,2],[0,2,1]],"r":2,"c":2,"returned":3,"expected":2,"frontier":[[2,1]]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const rows = grid.length;\nconst cols = grid[0].length;\nconst directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];\nlet head = 0;\nwhile (head < queue.length) {\n    const [r, c, distance] = queue[head];\n    head++;\n    for (const [dr, dc] of directions) {\n        const nr = r + dr;\n        const nc = c + dc;\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            if (grid[nr][nc] === 1) {\n                return (distance + 1);\n            }\n            if (grid[nr][nc] === 0) {\n                grid[nr][nc] = 2;\n                queue.push([nr, nc, (distance + 1)]);\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":11,"13":12,"14":13,"15":15,"16":16,"17":17,"18":22},"statementBundles":{"14":{"startLine":13,"endLine":14},"17":{"startLine":17,"endLine":21}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const rows = grid.length;\nconst cols = grid[0].length;\nconst directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];\nlet head = 0;\nwhile (head < queue.length) {\n    const [r, c, distance] = queue[head];\n    head++;\n    for (const [dr, dc] of directions) {\n        const nr = r + dr;\n        const nc = c + dc;\n        if (0 <= nr && nr < rows && 0 <= nc && nc < cols) {\n            if (grid[nr][nc] === 1) {\n                return (distance + 1);\n            }\n            if (grid[nr][nc] === 0) {\n                grid[nr][nc] = 2;\n                queue.push([nr, nc, (distance + 1)]);\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":11,"13":12,"14":13,"15":15,"16":16,"17":17,"18":22},"statementBundles":{"14":{"startLine":13,"endLine":14},"17":{"startLine":17,"endLine":21}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int rows = grid.size();\nint cols = grid.get(0).size();\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))));\nint head = 0;\nwhile (head < queue.size()) {\n    List<Integer> item = queue.get(head);\n    int r = item.get(0);\n    int c = item.get(1);\n    int distance = item.get(2);\n    head++;\n    for (List<Integer> direction : directions) {\n        int dr = direction.get(0);\n        int dc = direction.get(1);\n        int nr = r + dr;\n        int nc = c + dc;\n        if (((0 <= nr && nr < rows) && (0 <= nc && nc < cols))) {\n            if (grid.get(nr).get(nc) == 1) {\n                return (distance + 1);\n            }\n            if (grid.get(nr).get(nc) == 0) {\n                grid.get(nr).set(nc, 2);\n                queue.add(new ArrayList<>(List.of(nr, nc, (distance + 1))));\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":10,"9":11,"10":14,"11":15,"12":16,"13":17,"14":18,"15":20,"16":21,"17":22,"18":27},"statementBundles":{"7":{"startLine":6,"endLine":9},"9":{"startLine":11,"endLine":13},"14":{"startLine":18,"endLine":19},"17":{"startLine":22,"endLine":26}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int rows = grid.Count;\nint cols = grid[0].Count;\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 } };\nint head = 0;\nwhile (head < queue.Count) {\n    int r = queue[head][0];\n    int c = queue[head][1];\n    int distance = queue[head][2];\n    head++;\n    foreach (var item in directions) {\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            if (grid[nr][nc] == 1) {\n                return distance + 1;\n            }\n            if (grid[nr][nc] == 0) {\n                grid[nr][nc] = 2;\n                queue.Add(new List<int> { nr, nc, distance + 1 });\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":9,"9":10,"10":13,"11":14,"12":15,"13":16,"14":17,"15":19,"16":20,"17":21,"18":26},"statementBundles":{"7":{"startLine":6,"endLine":8},"9":{"startLine":10,"endLine":12},"14":{"startLine":17,"endLine":18},"17":{"startLine":21,"endLine":25}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int rows = grid.size();\nint cols = grid[0].size();\nvector<vector<int>> directions{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\nsize_t head = 0;\nwhile (head < queue.size()) {\n    auto values = queue[static_cast<int>(head)];\n    int r = values[0];\n    int c = values[1];\n    int distance = values[2];\n    head++;\n    for (vector<int> item : directions) {\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            if (grid[nr][nc] == 1) {\n                return (distance + 1);\n            }\n            if (grid[nr][nc] == 0) {\n                grid[nr][nc] = 2;\n                queue.push_back(vector<int>{nr, nc, (distance + 1)});\n            }\n        }\n    }\n}\nreturn -1;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":10,"9":11,"10":14,"11":15,"12":16,"13":17,"14":18,"15":20,"16":21,"17":22,"18":27},"statementBundles":{"7":{"startLine":6,"endLine":9},"9":{"startLine":11,"endLine":13},"14":{"startLine":18,"endLine":19},"17":{"startLine":22,"endLine":26}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Coloring one island and rippling outward found the shortest bridge on the sample grid, the first ring to touch the far island giving its length.","Two grids deserve a look before you code: islands that touch only on a diagonal, and one island wrapped around the other with a ring of water between them."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"grid":[[0,1,0],[0,0,0],[0,0,1]],"frontier":[[0,1],[2,2]]}}]}},{"id":"diagonal-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"When two land cells touch only on a diagonal, are they one island?","summary":"In grid = [[0,1],[1,0]] the cells (0,1) and (1,0) meet at a corner.","workspacePanel":"visualizer","options":[{"id":"separate","label":"No, they are two islands, and the answer is 1","rationale":"An island joins cells only up, down, left, and right, so a diagonal touch does not connect them. Coloring from (0,1) stops at (0,1), and one flip bridges the gap.","isCorrect":true},{"id":"one-island","label":"Yes, the diagonal touch makes them one island","rationale":"Diagonal contact does not count as connected. If the coloring sweep followed diagonals, it would swallow both islands and leave nothing to bridge to.","isCorrect":false},{"id":"zero","label":"They are separate, but the answer is 0","rationale":"Separate islands still need a bridge. A diagonal touch is not a connection, so at least one water flip is required, giving 1.","isCorrect":false}],"answer":"Two islands, answer 1. Connection is only up, down, left, and right, so the diagonal pair stays separate and one flip joins them.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"diagonal-state","state":{"grid":[[0,1],[1,0]],"frontier":[[0,1],[1,0]]}}]}},{"id":"ring-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"One island sits inside a ring of the other. Does the search still work?","summary":"The center cell is one island, and the surrounding ring of land is the other, with a moat of water between them.","workspacePanel":"visualizer","options":[{"id":"colors-one","label":"Yes, coloring the whole first island keeps the moat as searchable water","rationale":"The depth-first sweep colors only the connected component it starts in, so the inner island and the ring stay separate. The moat between them is still flippable water for the rings to cross.","isCorrect":true},{"id":"merges","label":"No, the coloring leaks across the moat and joins both","rationale":"The sweep stops at water and only follows land, so it cannot cross the moat. The two components stay distinct, which is exactly what the bridge search needs.","isCorrect":false},{"id":"no-water","label":"No, the ring leaves no water to flip","rationale":"The moat between the inner island and the ring is the water the bridge crosses. The search rings out across it just as on any other grid.","isCorrect":false}],"answer":"It works. The sweep colors only the one connected island it starts in, so the moat stays as water the outward rings cross to reach the other component.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ring-state","state":{"grid":[[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]],"frontier":[[2,2]]}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Color one island, then ripple out","summary":"Seed the whole island as one layer, and the first ring to touch the far island carries the answer.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[0,2,0],[0,0,0],[0,0,1]],"frontier":[[0,1]]}}]},"body":["Scan for the first land cell, then sweep its whole island with depth-first recursion, coloring each cell and seeding it into the search at distance 0. Grow rings of fresh water outward, each cell carrying one more flip than the cell it came from. The first time a ring is about to step onto the second island's original land, return the distance that cell carries."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the island-then-bridge search","eyebrow":"Code the rule","summary":"First color one island, then ripple rings of water out to the other.","workspacePanel":"code","checkpoints":[{"id":"find-first-island","title":"Find a first island cell","description":"Scan the grid until you find a land cell that can seed the first island traversal.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops","readMode":"grid-enumeration-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"gates_fresh_cell_before_component_entry","scope":"check-land","readMode":"grid-recursive-search-value-query-v1"}]}]},"commonMistakes":["Starting from water","Continuing to mark both islands before BFS"],"hint":"The first `1` you find can seed the first island; stop looking once that island has been marked.","semanticSpec":{"intent":"Locate a land cell and gate the first component traversal on that land check.","doneWhen":"The grid scan finds a `1` and uses it as the DFS entry point.","mustProve":["The grid is scanned by row and column.","DFS starts only after checking that the current cell is land."],"mustNotAccept":["DFS from every cell without a land gate."],"proofSnippets":[{"id":"py-shortest-bridge-find-first-island","language":"python","code":"def shortestBridge(grid: list[list[int]]) -> int:\n    for r in range(len(grid)):\n        for c in range(len(grid[0])):\n            if grid[r][c] == 1:\n                return 0"}],"roles":["grid scan","first island cell"]}},{"id":"mark-first-island","title":"Mark the first island","description":"Use DFS from the first land cell to mark every cell in that island and avoid revisiting it.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_recursive_cell_exploration","scope":"call-dfs","readMode":"grid-recursive-search-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"guards_boundary_before_exploration","scope":"dfs-base-case","readMode":"grid-recursive-search-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"explores_grid_neighbors","scope":"explore-neighbors","readMode":"grid-recursive-search-value-query-v1"}]}]},"commonMistakes":["Only marking the starting cell","Letting DFS cross water into the other island"],"hint":"DFS should stop on water or marked cells and recurse only through 4-directional land.","semanticSpec":{"intent":"Consume the first connected component before BFS begins.","doneWhen":"A recursive grid helper marks the whole first island and stops at water, bounds, or already-marked cells.","mustProve":["The recursive helper has boundary/cell guards.","The helper explores neighboring grid cells."],"mustNotAccept":["A helper that cannot reach all cells of the first island."],"roles":["DFS helper","first island","marked cells"]}},{"id":"seed-bfs-frontier","title":"Seed BFS from the marked island","description":"Add first-island cells to a queue with distance 0 so the bridge expands from the entire island at once.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"initializes_frontier_and_aux_state","scope":"init-queue","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Enqueueing only one island cell","Starting distance at 1"],"hint":"Every cell of the first island can be a distance-0 starting point.","semanticSpec":{"intent":"Initialize the BFS frontier from the first island.","doneWhen":"The queue is initialized and populated with island cells carrying a distance state.","mustProve":["A BFS frontier is initialized before the traversal loop."],"mustNotAccept":["A BFS loop with no seeded frontier."],"roles":["frontier queue","distance"]}},{"id":"bfs-loop","title":"Expand BFS layers","description":"Process queued cells in FIFO order so each water layer represents one additional flip.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"loops_while_frontier_non_empty","scope":"bfs-loop","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Using DFS for the expansion","Losing the distance value carried by each queued cell"],"hint":"The first time BFS reaches the second island is the shortest bridge.","semanticSpec":{"intent":"Drive the bridge expansion with FIFO BFS.","doneWhen":"The queue is repeatedly dequeued until a terminal condition is reached.","mustProve":["A frontier loop consumes queued states in BFS order."],"mustNotAccept":["A stack-like expansion."],"roles":["frontier queue","distance layer"]}},{"id":"check-neighbors","title":"Check four neighboring cells","description":"From each BFS cell, inspect the four cardinal neighbors and skip invalid or already-marked cells.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"expands_frontier_neighbors","scope":"check-neighbors","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Including diagonals","Forgetting bounds checks","Revisiting the first island"],"hint":"Only unmarked in-bounds neighbors are candidates for expansion or termination.","semanticSpec":{"intent":"Evaluate the four orthogonal expansion choices from each frontier cell.","doneWhen":"BFS checks up, down, left, and right with bounds and visited guards.","mustProve":["The frontier expansion iterates over neighboring grid coordinates."],"mustNotAccept":["Diagonal expansion."],"roles":["neighbor coordinates","visited guard"]}},{"id":"enqueue-water","title":"Enqueue water as the next layer","description":"When BFS finds water, mark it and enqueue it with distance + 1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"enqueues_derived_frontier_state","scope":"rot-fresh","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Not marking water before enqueueing it","Reusing the same distance instead of distance + 1"],"hint":"A water cell added to the queue represents one more flip than the current cell.","semanticSpec":{"intent":"Schedule newly reached water cells as the next bridge layer.","doneWhen":"Each accepted water neighbor is marked and enqueued with incremented distance.","mustProve":["A derived neighbor state is enqueued from the current frontier state."],"mustNotAccept":["Constant or stale enqueue payloads."],"roles":["water neighbor","next distance"]}},{"id":"return-distance","title":"Return when the second island is reached","description":"The first second-island cell reached by BFS gives the shortest bridge length.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bfs-queue","fact":"returns_terminal_result_during_frontier_expansion","scope":"return-result","readMode":"bfs-queue-value-query-v1"}]},"commonMistakes":["Returning distance + 1 when the neighbor is already land","Continuing BFS after reaching the second island"],"hint":"When a frontier cell touches original land from the second island, the current distance is the number of water cells flipped.","semanticSpec":{"intent":"Stop at the first contact with the second island and return the BFS distance.","doneWhen":"A terminal return occurs during frontier expansion when an unmarked land neighbor is found.","mustProve":["The BFS expansion returns its distance result when the target island is reached."],"mustNotAccept":["Returning after all layers without detecting second-island contact."],"roles":["second island","BFS distance","terminal return"]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Color one island, then ripple water out from all of it at once; the first touch on the other island is the bridge.","workspacePanel":"code","body":["The two phases each do one job: a depth-first sweep colors the first whole island, and a breadth-first ripple grows the shortest bridge from it.","Seeding every island cell as one starting layer makes the rings count flips, so the first ring to reach the second island gives the answer directly."],"takeaways":[{"title":"Seed the whole shore, not one cell","body":"The shortest crossing can leave the island from anywhere, so seeding every island cell at distance 0 lets one search find the nearest reach without guessing where."},{"title":"Contact returns the distance, not one more","body":"The cell that touches the far island already counts the water flipped to reach it, and the island's land is no flip, so the bridge is that distance."},{"title":"Both phases are one grid sweep each","body":"Coloring touches each island cell once and the ripple touches each water cell once, so the whole solution is O(n^2), far below the all-pairs O(n^4)."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
