{"id":"number-of-closed-islands","title":"Number of Closed Islands","difficulty":"medium","patterns":["graph-dfs"],"primaryConcept":"graph-grid-fill","concepts":["graph-grid-fill","graph-components"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"grid","sizeMetric":"matrix-cells","constraints":["binary-int","zero-is-land","closed-components"],"sizes":[9,25,64,144]},"description":"You are given an `m x n` grid where `0` is land and `1` is water.\n\nA closed island is a 4-directionally connected group of `0` cells that is completely surrounded by `1` cells and does not touch the grid border. Return the number of closed islands.","examples":[{"input":"grid = [[1,1,1],[1,0,1],[1,1,1]]","output":"1","explanation":"The center land cell is surrounded by water."},{"input":"grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]","output":"1","explanation":"Only the middle land cell is closed; the land touching the border is not closed."},{"input":"grid = [[1,1,1,1],[1,0,0,1],[1,0,0,1],[1,1,1,1]]","output":"1","explanation":"The 2x2 land region is one closed island."}],"constraints":[{"id":"1-len-grid-len-grid-i-100","text":"1 <= len(grid), len(grid[i]) <= 100","check":[{"kind":"sizeRange","target":"grid","measure":"matrixRows","min":1,"max":100},{"kind":"valueRange","target":"grid","selector":"arrayItemLengths","min":1,"max":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":"0-represents-land-and-1-represents-water","text":"0 represents land and 1 represents water"}],"starterCode":"class Solution:\n    def closedIsland(self, grid: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"closedIsland","testCases":[{"id":"1","input":{"grid":[[1,1,1],[1,0,1],[1,1,1]]},"expected":1,"description":"Single-cell closed island."},{"id":"2","input":{"grid":[[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]},"expected":1,"description":"Border-connected land is excluded."},{"id":"3","input":{"grid":[[1,1,1,1],[1,0,0,1],[1,0,0,1],[1,1,1,1]]},"expected":1,"description":"One larger closed island."},{"id":"4","input":{"grid":[[1,1,1,1,1],[1,0,1,0,1],[1,1,1,1,1]]},"expected":2,"description":"Two separate closed single-cell islands."},{"id":"5","input":{"grid":[[0,1,1],[1,0,1],[1,1,1]]},"expected":1,"description":"Diagonal border land does not connect to the center."},{"id":"h1","input":{"grid":[[0]]},"expected":0,"description":"Single border land cell is not closed."},{"id":"h2","input":{"grid":[[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]},"expected":2,"description":"Classic larger case with two closed islands."},{"id":"h3","input":{"grid":[[1,1,1,1],[1,1,1,1]]},"expected":0,"description":"No land cells."},{"id":"h4","input":{"grid":[[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,1,1,1,1]]},"expected":2,"description":"Two separate single-cell closed islands."},{"id":"h5","input":{"grid":[[1,1,1,1,1],[1,0,1,0,1],[1,1,1,1,1],[1,0,1,0,1],[1,1,1,1,1]]},"expected":4,"description":"Four isolated closed islands can coexist in one grid."},{"id":"topup-two-closed-basins","input":{"grid":[[1,1,1,1,1,1],[1,0,0,1,0,1],[1,0,1,1,0,1],[1,1,1,1,1,1]]},"expected":2,"description":"Two separated land basins are fully enclosed."},{"id":"topup-open-to-border","input":{"grid":[[0,1,1],[0,0,1],[1,1,1]]},"expected":0,"description":"A land region connected to the border is not closed."},{"id":"land-reaches-right-border","input":{"grid":[[1,1,1],[1,0,0],[1,1,1]]},"expected":0,"description":"The only land reaches the right border, so it is not a closed island."}],"hints":[{"level":1,"content":"Any land connected to the border cannot be part of a closed island.","revealPattern":false},{"level":2,"content":"First flood-fill all border-connected land cells so they will not be counted later.","revealPattern":true},{"level":3,"content":"After the border flood, every remaining unvisited land component is closed. Count it and flood it too.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"border-flood","name":"Border flood-fill, then count","summary":"Flood every blob reachable from a border to sink the open land, then count each land blob that remains.","decisionReason":"Sinking the open land first removes the need to test each blob for border contact, so the second pass just counts survivors in one linear sweep.","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Visits each cell a constant number of times and uses recursion stack space up to the grid size."],"isOptimal":true},{"id":"per-blob-flag","name":"Flood each blob with a border flag","summary":"Walk every land blob once, threading a flag that records whether any of its cells sat on the border, and count only the blobs whose flag stayed false.","decisionReason":"A boundary flag on each flood returns the same closed-island count in O(m*n) time. The trace floods border land first so interior floods need no threaded flag or end-of-search verdict.","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Carries a mutable border flag through every recursive call and reads it after each blob finishes."],"isViable":true,"isOptimal":false}]},"codingCheckpoints":[{"id":"border-flood","title":"Flood border-connected land","description":"Run DFS from border cells so any land touching the border is removed before counting.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_recursive_cell_exploration","scope":"call-dfs","readMode":"grid-recursive-search-value-query-v1"}]},"commonMistakes":["Counting border land as closed","Only checking the top and left borders"],"hint":"Call DFS from all four borders before scanning the interior.","semanticSpec":{"intent":"Start recursive grid exploration from grid cells before the closed-island count.","doneWhen":"The code invokes a DFS-style helper on grid coordinates.","shouldFailWhen":"This step should fail if no recursive cell exploration is started.","roles":["border cells","DFS helper"],"mustProve":["The solution starts recursive exploration from grid coordinates."],"mustNotAccept":["Counting cells without any connected-component traversal."]}},{"id":"dfs-base-case","title":"Stop DFS outside land","description":"Stop recursion when the cell is outside the grid or is not land.","validation":{"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"}]},"commonMistakes":["Reading grid cells before checking bounds","Letting DFS cross water"],"hint":"Check bounds before looking at `grid[r][c]`.","semanticSpec":{"intent":"Guard recursive grid exploration with boundary and cell-state checks.","doneWhen":"The DFS helper returns before exploring out-of-bounds cells.","shouldFailWhen":"This step should fail if the helper can recurse outside the grid.","roles":["boundary guard","cell-state guard"],"mustProve":["The recursive helper checks grid boundaries."],"mustNotAccept":["A DFS helper with no boundary guard."]}},{"id":"explore-neighbors","title":"Explore four neighbors","description":"From each land cell, recurse into its four orthogonal neighbors.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"explores_grid_neighbors","scope":"explore-neighbors","readMode":"grid-recursive-search-value-query-v1"}]},"commonMistakes":["Exploring only one direction","Using diagonal neighbors"],"hint":"Use up, down, left, and right moves.","semanticSpec":{"intent":"Traverse each connected land component by recursive neighbor exploration.","doneWhen":"DFS recurses to neighboring grid cells.","shouldFailWhen":"This step should fail if recursion does not move through grid neighbors.","roles":["neighbor cells","component traversal"],"mustProve":["The recursive helper explores adjacent grid coordinates."],"mustNotAccept":["Only checking the current cell."]}},{"id":"scan-interior","title":"Scan the remaining grid","description":"After the border flood, scan the grid for land components that remain.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops","readMode":"grid-enumeration-value-query-v1"}]},"commonMistakes":["Only scanning the border","Stopping after the first closed island"],"hint":"Use nested row and column loops for the counting pass.","semanticSpec":{"intent":"Enumerate grid cells to find remaining land components.","doneWhen":"The solution uses nested loops over grid rows and columns.","shouldFailWhen":"This step should fail if the counting pass does not traverse grid cells.","roles":["row loop","column loop","grid cells"],"mustProve":["The grid is scanned by row and column."],"mustNotAccept":["A single-cell check with no grid traversal."]}},{"id":"count-closed-island","title":"Return the closed-island count","description":"When an unvisited land cell remains, count one closed island, flood that component, and return the completed count.","validation":{"type":"semantic","validator":"all","params":[{"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"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_updated_zero_numeric_state","scope":"count-closed-island","readMode":"numeric-state-value-query-v1"}]}]},"commonMistakes":["Counting every land cell instead of each component","Forgetting to flood the counted component"],"hint":"Only increment when you find the first cell of a remaining land component, then DFS from it; return the count after the scan.","semanticSpec":{"intent":"Count closed components by gating DFS entry on remaining land.","doneWhen":"The code initializes a count, checks for a remaining land cell, increments once per component, starts DFS from that cell, and returns the completed count.","shouldFailWhen":"This step should fail if the count is not initialized or if DFS is not gated by a land check.","roles":["closed-island count","remaining land","component entry"],"mustProve":["The count starts from zero.","Component traversal starts only after a land-cell check.","The completed count is returned."],"mustNotAccept":["Counting water cells.","Incrementing without a component-entry gate."]}}],"slides":[{"id":"read-the-problem","chapter":"The map","kind":"info","eyebrow":"Read the problem","title":"Count the islands that never reach the edge","workspacePanel":"problem","body":["You get a grid where 0 is land and 1 is water. A closed island is a group of land cells joined edge to edge that is fully ringed by water and never touches the outer border of the grid.","Land that touches any edge is open, no matter how much water surrounds the rest of it."]},{"id":"naive-flag","chapter":"The obvious way","kind":"code-trace","eyebrow":"Try the direct way","title":"Test each blob: did it touch the edge?","workspacePanel":"trace","summary":"The direct reading of the problem is to find each land blob, walk it, and watch whether any cell of it sits on the border. Count the blob only if the walk never hit an edge.","codeTrace":{"contract":"guided-code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def count_closed(grid: list[list[int]], rows: int, cols: int) -> int:\n    def touches_border(r: int, c: int) -> bool:\n        if r < 0 or r >= rows or c < 0 or c >= cols:\n            return True\n        if grid[r][c] == 1:\n            return False\n        grid[r][c] = 1\n        edge = r == 0 or r == rows - 1 or c == 0 or c == cols - 1\n        a = touches_border(r + 1, c)\n        b = touches_border(r - 1, c)\n        e = touches_border(r, c + 1)\n        f = touches_border(r, c - 1)\n        return edge or a or b or e or f\n    count = 0\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 0:\n                if not touches_border(r, c):\n                    count += 1\n    return count","steps":[{"id":"find-blob","title":"Find a fresh land blob","codeLine":17,"summary":"The scan reaches the left-edge land at (0,0). It is a 0, so a walk of this blob starts here to find out whether it reaches an edge.","state":{"grid":[[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]],"r":0,"c":0,"count":0}},{"id":"walk-hits-edge","title":"The walk reaches the border","codeLine":8,"summary":"Walking this blob covers the whole left column. Cell (0,0) sits in row 0, an edge row, so the edge flag is true and the walk will report the blob as open.","state":{"grid":[[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]],"r":0,"c":0,"filled":[[0,0],[1,0],[2,0]],"changed":[[0,0],[1,0],[2,0]],"count":0}},{"id":"reject-open","title":"Border touched, so skip it","codeLine":18,"summary":"touches_border came back true, so this blob is open and the count stays 0. The scan moves on to the next unwalked land.","state":{"grid":[[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]],"r":0,"c":0,"filled":[[0,0],[1,0],[2,0]],"changed":[],"count":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function touchesBorder(r, c) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols) {\n        return true;\n    }\n    if (grid[r][c] === 1) {\n        return false;\n    }\n    grid[r][c] = 1;\n    const edge = (((r === 0) || (r === (rows - 1))) || (c === 0)) || (c === (cols - 1));\n    const a = touchesBorder((r + 1), c);\n    const b = touchesBorder((r - 1), c);\n    const e = touchesBorder(r, (c + 1));\n    const f = touchesBorder(r, (c - 1));\n    return ((((edge || a) || b) || e) || f);\n}\nlet count = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (grid[r][c] === 0) {\n            if (!touchesBorder(r, c)) {\n                count++;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":16,"15":17,"16":18,"17":19,"18":20,"19":21,"20":26},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"13":{"startLine":14,"endLine":15},"19":{"startLine":21,"endLine":25}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function touchesBorder(r: number, c: number): boolean {\n    if (r < 0 || r >= rows || c < 0 || c >= cols) {\n        return true;\n    }\n    if (grid[r][c] === 1) {\n        return false;\n    }\n    grid[r][c] = 1;\n    const edge = (((r === 0) || (r === (rows - 1))) || (c === 0)) || (c === (cols - 1));\n    const a = touchesBorder((r + 1), c);\n    const b = touchesBorder((r - 1), c);\n    const e = touchesBorder(r, (c + 1));\n    const f = touchesBorder(r, (c - 1));\n    return ((((edge || a) || b) || e) || f);\n}\nlet count = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (grid[r][c] === 0) {\n            if (!touchesBorder(r, c)) {\n                count++;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":16,"15":17,"16":18,"17":19,"18":20,"19":21,"20":26},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"13":{"startLine":14,"endLine":15},"19":{"startLine":21,"endLine":25}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"bool TouchesBorder(int r, int c) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols) {\n        return true;\n    }\n    if (grid[r][c] == 1) {\n        return false;\n    }\n    grid[r][c] = 1;\n    bool edge = r == 0 || r == rows - 1 || c == 0 || c == cols - 1;\n    bool a = TouchesBorder(r + 1, c);\n    bool b = TouchesBorder(r - 1, c);\n    bool e = TouchesBorder(r, c + 1);\n    bool f = TouchesBorder(r, c - 1);\n    return edge || a || b || e || f;\n    return false;\n}\nint count = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (grid[r][c] == 0) {\n            if (!TouchesBorder(r, c)) {\n                count++;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":17,"15":18,"16":19,"17":20,"18":21,"19":22,"20":27},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"13":{"startLine":14,"endLine":16},"19":{"startLine":22,"endLine":26}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<bool(int, int)> touches_border;\n\ntouches_border = [&]( int r, int c ) -> bool {\n    if ((((r < 0 || r >= rows) || c < 0) || c >= cols)) {\n        return true;\n    }\n    if (grid[r][c] == 1) {\n        return false;\n    }\n    grid[r][c] = 1;\n    bool edge = ((r == 0 || r == (rows - 1)) || c == 0) || c == (cols - 1);\n    bool a = touches_border((r + 1), c);\n    bool b = touches_border((r - 1), c);\n    bool e = touches_border(r, (c + 1));\n    bool f = touches_border(r, (c - 1));\n    return ((((edge || a) || b) || e) || f);\n};\nint count = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (grid[r][c] == 0) {\n            if (!touches_border(r, c)) {\n                count++;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"3":4,"4":5,"5":7,"6":8,"7":10,"8":11,"9":12,"10":13,"11":14,"12":15,"13":16,"14":18,"15":19,"16":20,"17":21,"18":22,"19":23,"20":28},"statementBundles":{"4":{"startLine":5,"endLine":6},"6":{"startLine":8,"endLine":9},"13":{"startLine":16,"endLine":17},"19":{"startLine":23,"endLine":27}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static boolean touchesBorder(int r, int c, int rows, int cols, List<List<Integer>> grid) {\n    if ((((r < 0 || r >= rows) || c < 0) || c >= cols)) {\n        return true;\n    }\n    if (grid.get(r).get(c) == 1) {\n        return false;\n    }\n    grid.get(r).set(c, 1);\n    boolean edge = ((r == 0 || r == (rows - 1)) || c == 0) || c == (cols - 1);\n    boolean a = touchesBorder((r + 1), c, rows, cols, grid);\n    boolean b = touchesBorder((r - 1), c, rows, cols, grid);\n    boolean e = touchesBorder(r, (c + 1), rows, cols, grid);\n    boolean f = touchesBorder(r, (c - 1), rows, cols, grid);\n    return ((((edge || a) || b) || e) || f);\n}\n\nint count = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (grid.get(r).get(c) == 0) {\n            if (!touchesBorder(r, c, rows, cols, grid)) {\n                count++;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":17,"15":18,"16":19,"17":20,"18":21,"19":22,"20":27},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"13":{"startLine":14,"endLine":15},"19":{"startLine":22,"endLine":26}}}}}},{"id":"naive-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Weigh the cost","title":"What does the touched flag force every walk to do?","summary":"Each blob needs its border verdict threaded out before the count can move.","workspacePanel":"trace","options":[{"id":"whole-blob","label":"Carry a touched flag through every recursive call and read its verdict only after the walk has covered the whole blob","rationale":"The flag has to ride along on every cell of the walk and combine through each recursive return, and the verdict is only valid once the full blob is marked. Lose one return on one branch and a closed blob can read as open, or an open one as closed.","isCorrect":true},{"id":"stop-early","label":"Stop the walk the instant a border cell is seen","rationale":"Stopping early leaves the rest of the blob unmarked, so the scan would re-enter it and test the same blob again. The walk cannot quit until the blob is fully marked.","isCorrect":false},{"id":"no-walk","label":"Decide closure from the blob's first cell alone","rationale":"A single cell cannot show whether another cell in the same blob reaches an edge. You have to walk the connected shape before declaring it closed.","isCorrect":false}],"answer":"Every walk still costs the same O(rows*cols) sweep over the cells, but each one has to thread a touched flag through every recursive return and read the verdict at the end. That per-blob flag is fragile bookkeeping: one missed return and the count is wrong."},{"id":"the-flip","chapter":"The trick","kind":"case-probe","eyebrow":"Find the move","title":"What could you remove from the grid so the count needs no flag?","summary":"The baseline carried a touched flag because any blob might reach an edge. What if that uncertainty were gone before the count began?","workspacePanel":"visualizer","options":[{"id":"remaining-closed","label":"Then every land blob still standing is closed, so you can count them with no flag at all","rationale":"Open means reachable from the border. Flooding from every border cell sinks all of that land first, so whatever land remains was never reachable from an edge. The closure test is now just \"is there still land here?\".","isCorrect":true},{"id":"lose-closed","label":"You would also erase the closed islands, leaving nothing to count","rationale":"A closed island is unreachable from the border by definition, so a flood that starts only at border cells can never reach it. Only the open land disappears.","isCorrect":false},{"id":"still-need-flag","label":"You would still need the touched flag on the second pass","rationale":"Once the open land is gone, any leftover land is guaranteed closed. There is nothing left to test, so the flag is no longer needed.","isCorrect":false}],"answer":"Flood from every border cell first. That sinks all the open land, so every blob that survives is closed and you just count the survivors, no per-blob flag required.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-flip-state","state":{"grid":[[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]],"filled":[[0,0],[0,1],[1,0],[2,0],[0,3],[0,4],[1,4],[2,4],[2,1],[2,2],[2,3]],"changed":[]}}]}},{"id":"two-passes","chapter":"The trick","kind":"info","eyebrow":"Hold the idea","title":"Erase the open land, then count what is left","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-passes-state","state":{"grid":[[1,1,1,1,1],[1,1,0,1,1],[1,1,1,1,1]],"filled":[[0,0],[0,1],[1,0],[2,0],[0,3],[0,4],[1,4],[2,4],[2,1],[2,2],[2,3]],"changed":[],"count":0}}]},"body":["The first pass floods from every cell on the four borders, sinking all the land those floods can reach. After it, only the center cell at row 1 column 2 is still land, walled in on all sides.","The second pass sweeps the interior. Each surviving land cell starts a fresh closed island, so the count goes up and that blob is flooded to keep the sweep from meeting it twice. Both passes use the same four-direction flood; only the starting cells differ."]},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Border flood first, then count the survivors","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-setup-state","state":{"grid":[[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]],"count":0}}]},"body":["The count starts at 0. First the border flood runs and sinks every land cell reachable from an edge.","Then the interior sweep walks the cells away from the border. On water it keeps moving; on land it adds 1 and floods that blob away before going on."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the passes","title":"Trace the two passes","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-border-flood","state":{"grid":[[1,1,1,1,1],[1,1,0,1,1],[1,1,1,1,1]],"filled":[[0,0],[0,1],[1,0],[2,0],[0,3],[0,4],[1,4],[2,4],[2,1],[2,2],[2,3]],"changed":[],"count":0}},{"id":"count-center","state":{"grid":[[1,1,1,1,1],[1,1,0,1,1],[1,1,1,1,1]],"r":1,"c":2,"filled":[[0,0],[0,1],[1,0],[2,0],[0,3],[0,4],[1,4],[2,4],[2,1],[2,2],[2,3]],"changed":[],"count":0}},{"id":"final","state":{"grid":[[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]],"r":1,"c":2,"filled":[[0,0],[0,1],[1,0],[2,0],[0,3],[0,4],[1,4],[2,4],[2,1],[2,2],[2,3],[1,2]],"changed":[[1,2]],"count":1}}]},"beats":[{"id":"after-border-flood","title":"After the border flood, which cell is still land?","summary":"Every flood started from a border cell and sank what it could reach.","prompt":"The four borders have all been flooded.","options":[{"id":"center","label":"Only the center cell at row 1 column 2","rationale":"All the edge-reaching land was sunk, and the center cell sits behind water on every side, so the border floods never reached it. It is the lone survivor.","isCorrect":true},{"id":"none","label":"No land at all","rationale":"The center cell is unreachable from any border, so no border flood could touch it. It is still land.","isCorrect":false},{"id":"all-left","label":"The whole left column","rationale":"The left column is itself on the border, so it was the first land the flood sank. It is gone.","isCorrect":false}],"answer":"Only the center cell survives. Every other land cell was reachable from an edge, so the border floods sank all of it."},{"id":"count-center","title":"The sweep reaches that surviving cell. What does it do?","summary":"The interior sweep finds land at row 1 column 2, and the count is still 0.","prompt":"The sweep lands on the surviving center cell.","options":[{"id":"count-flood","label":"Add 1 and flood the cell away","rationale":"Any land left after the border flood is closed, so this is a closed island. The count becomes 1, and flooding the cell keeps the sweep from counting it again.","isCorrect":true},{"id":"test-first","label":"Walk it first to check it never touches an edge","rationale":"The border flood already removed everything that touches an edge, so a survivor cannot be open. No further test is needed.","isCorrect":false},{"id":"skip","label":"Skip it, since it might still be open","rationale":"It survived the border flood, which means it was never reachable from an edge. It is closed, and skipping it would lose a real island.","isCorrect":false}],"answer":"Add 1 and flood it. A survivor of the border flood is closed by construction, so the count rises to 1."},{"id":"final","title":"The sweep has one closed island so far. What does it find in the rest of the interior?","summary":"The center cell has been counted and flooded. The sweep still has to finish the remaining interior cells before returning.","prompt":"The sweep continues past the center toward the end of the grid.","options":[{"id":"nothing-more","label":"Nothing more, so it returns the count it already has","rationale":"Every other cell the sweep meets is water from the border flood, so no new component starts. The count stays where the center put it and that value is returned.","isCorrect":true},{"id":"recount-center","label":"It meets the center again and adds another count","rationale":"The center was flooded the moment it was counted, so the sweep now reads it as water and never re-enters it. It is counted exactly once.","isCorrect":false},{"id":"find-more","label":"It finds another closed island in the leftover water","rationale":"Only one blob survived the border flood. Every remaining cell is water, so there is no second component to count.","isCorrect":false}],"answer":"Nothing more. The rest of the interior is water, so no new component starts and the sweep returns the count it already holds."}]},{"id":"border-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Is flooding from the top and left borders enough?","workspacePanel":"trace","summary":"A broken version floods only the top row and left column before counting. Those two edges catch open land that starts there. Watch it on a blob that reaches only the right edge.","pitfall":"The flood below seeds only the top row and the left column, never the bottom row or the right column.","whyItMatters":"A blob that touches only the right or bottom edge is open, but a flood that never starts there never reaches it. It survives into the interior pass, gets counted as closed, and the answer comes out too high. The fix is to seed the flood from all four borders before the interior sweep, so every edge-reaching blob is sunk no matter which edge it meets.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def count_with_partial_border(grid: list[list[int]], rows: int, cols: int) -> int:\n    def dfs(r: int, c: int) -> None:\n        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 1:\n            return\n        grid[r][c] = 1\n        dfs(r + 1, c)\n        dfs(r - 1, c)\n        dfs(r, c + 1)\n        dfs(r, c - 1)\n    for c in range(cols):\n        dfs(0, c)\n    for r in range(rows):\n        dfs(r, 0)\n    count = 0\n    for r in range(1, rows - 1):\n        for c in range(1, cols - 1):\n            if grid[r][c] == 0:\n                count += 1\n                dfs(r, c)\n    return count","steps":[{"id":"partial-flood","title":"Only the top and left edges are flooded","codeLine":13,"summary":"grid has a land strip at (1,1), (1,2), (1,3); the cell (1,3) sits on the right edge. The flood seeds the top row and left column, which are all water here, so nothing is sunk.","state":{"grid":[[1,1,1,1],[1,0,0,0],[1,1,1,1]],"r":1,"c":0,"count":0}},{"id":"miss-strip","title":"The right-edge blob is never reached","codeLine":17,"summary":"The interior sweep reaches (1,1), still land. Because the right border was never seeded, the strip that runs out to (1,3) is untouched, so the sweep reads it as a fresh closed island.","state":{"grid":[[1,1,1,1],[1,0,0,0],[1,1,1,1]],"r":1,"c":1,"count":1}},{"id":"wrong-total","title":"It returns 1 for a blob that touches the edge","codeLine":19,"summary":"The strip reaches the right border at (1,3), so it is open and should count for nothing. Missing two of the four borders let it through. The real answer is 0.","state":{"grid":[[1,1,1,1],[1,0,0,0],[1,1,1,1]],"r":1,"c":1,"count":1,"filled":[[1,1],[1,2],[1,3]],"changed":[[1,1],[1,2],[1,3]]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function dfs(r, c) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === 1) {\n        return;\n    }\n    grid[r][c] = 1;\n    dfs((r + 1), c);\n    dfs((r - 1), c);\n    dfs(r, (c + 1));\n    dfs(r, (c - 1));\n}\nfor (let c = 0; c < cols; c++) {\n    dfs(0, c);\n}\nfor (let r = 0; r < rows; r++) {\n    dfs(r, 0);\n}\nlet count = 0;\nfor (let r = 1; r < (rows - 1); r++) {\n    for (let c = 1; c < (cols - 1); c++) {\n        if (grid[r][c] === 0) {\n            count++;\n            dfs(r, c);\n        }\n    }\n}\nreturn count;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":11,"11":12,"12":14,"13":15,"14":17,"15":18,"16":19,"17":20,"18":21,"19":22,"20":26},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":10},"11":{"startLine":12,"endLine":13},"13":{"startLine":15,"endLine":16},"19":{"startLine":22,"endLine":25}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function dfs(r: number, c: number): void {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === 1) {\n        return;\n    }\n    grid[r][c] = 1;\n    dfs((r + 1), c);\n    dfs((r - 1), c);\n    dfs(r, (c + 1));\n    dfs(r, (c - 1));\n}\nfor (let c = 0; c < cols; c++) {\n    dfs(0, c);\n}\nfor (let r = 0; r < rows; r++) {\n    dfs(r, 0);\n}\nlet count = 0;\nfor (let r = 1; r < (rows - 1); r++) {\n    for (let c = 1; c < (cols - 1); c++) {\n        if (grid[r][c] === 0) {\n            count++;\n            dfs(r, c);\n        }\n    }\n}\nreturn count;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":11,"11":12,"12":14,"13":15,"14":17,"15":18,"16":19,"17":20,"18":21,"19":22,"20":26},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":10},"11":{"startLine":12,"endLine":13},"13":{"startLine":15,"endLine":16},"19":{"startLine":22,"endLine":25}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static void dfs(int r, int c, int rows, int cols, List<List<Integer>> grid) {\n    if (((((r < 0 || r >= rows) || c < 0) || c >= cols) || grid.get(r).get(c) == 1)) {\n        return;\n    }\n    grid.get(r).set(c, 1);\n    dfs((r + 1), c, rows, cols, grid);\n    dfs((r - 1), c, rows, cols, grid);\n    dfs(r, (c + 1), rows, cols, grid);\n    dfs(r, (c - 1), rows, cols, grid);\n}\n\nfor (int c = 0; c < cols; c++) {\n    dfs(0, c, rows, cols, grid);\n}\nfor (int r = 0; r < rows; r++) {\n    dfs(r, 0, rows, cols, grid);\n}\nint count = 0;\nfor (int r = 1; r < (rows - 1); r++) {\n    for (int c = 1; c < (cols - 1); c++) {\n        if (grid.get(r).get(c) == 0) {\n            count++;\n            dfs(r, c, rows, cols, grid);\n        }\n    }\n}\nreturn count;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":12,"11":13,"12":15,"13":16,"14":18,"15":19,"16":20,"17":21,"18":22,"19":23,"20":27},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":10},"11":{"startLine":13,"endLine":14},"13":{"startLine":16,"endLine":17},"19":{"startLine":23,"endLine":26}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"void Dfs(int r, int c) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == 1) {\n        return;\n    }\n    grid[r][c] = 1;\n    Dfs(r + 1, c);\n    Dfs(r - 1, c);\n    Dfs(r, c + 1);\n    Dfs(r, c - 1);\n}\nfor (int c = 0; c < cols; c++) {\n    Dfs(0, c);\n}\nfor (int r = 0; r < rows; r++) {\n    Dfs(r, 0);\n}\nint count = 0;\nfor (int r = 1; r < rows - 1; r++) {\n    for (int c = 1; c < cols - 1; c++) {\n        if (grid[r][c] == 0) {\n            count++;\n            Dfs(r, c);\n        }\n    }\n}\nreturn count;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":11,"11":12,"12":14,"13":15,"14":17,"15":18,"16":19,"17":20,"18":21,"19":22,"20":26},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":10},"11":{"startLine":12,"endLine":13},"13":{"startLine":15,"endLine":16},"19":{"startLine":22,"endLine":25}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<void(int, int)> dfs;\n\ndfs = [&]( int r, int c ) -> void {\n    if (((((r < 0 || r >= rows) || c < 0) || c >= cols) || grid[r][c] == 1)) {\n        return;\n    }\n    grid[r][c] = 1;\n    dfs((r + 1), c);\n    dfs((r - 1), c);\n    dfs(r, (c + 1));\n    dfs(r, (c - 1));\n};\nfor (int c = 0; c < cols; c++) {\n    dfs(0, c);\n}\nfor (int r = 0; r < rows; r++) {\n    dfs(r, 0);\n}\nint count = 0;\nfor (int r = 1; r < (rows - 1); r++) {\n    for (int c = 1; c < (cols - 1); c++) {\n        if (grid[r][c] == 0) {\n            count++;\n            dfs(r, c);\n        }\n    }\n}\nreturn count;","lineMap":{"3":4,"4":5,"5":7,"6":8,"7":9,"8":10,"9":11,"10":13,"11":14,"12":16,"13":17,"14":19,"15":20,"16":21,"17":22,"18":23,"19":24,"20":28},"statementBundles":{"4":{"startLine":5,"endLine":6},"9":{"startLine":11,"endLine":12},"11":{"startLine":14,"endLine":15},"13":{"startLine":17,"endLine":18},"19":{"startLine":24,"endLine":27}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"grid":[[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]],"count":0}}]},"body":["Flooding all four borders and then counting the survivors handled the sample cleanly. The order is what made the count cheap.","Two shapes are worth running before you code: land that only touches the border at a diagonal, and a grid with no land at all."]},{"id":"diagonal-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"A border cell sits diagonally next to interior land. Is that land still closed?","summary":"The panel highlights a corner 0 and another 0 one row and one column inward.","workspacePanel":"visualizer","options":[{"id":"closed","label":"Yes, the center cell is closed","rationale":"The flood moves only up, down, left, and right, so a diagonal is not a connection. The border flood sinks the corner cell but cannot cross to the center, which survives as a closed island.","isCorrect":true},{"id":"open","label":"No, the diagonal links it to the border","rationale":"Diagonal cells are not neighbors under four-direction adjacency, so the border flood never steps from the corner to the center. The link the eye sees is not a link the flood follows.","isCorrect":false},{"id":"depends","label":"Only if the corner cell is flooded first","rationale":"Flood order does not matter here. No sequence of up, down, left, right moves connects a diagonal pair, so the center is closed regardless.","isCorrect":false}],"answer":"Closed. The flood only crosses shared edges, so a diagonal never connects the center cell to the border, and it survives the border pass.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"diagonal-state","state":{"grid":[[0,1,1],[1,0,1],[1,1,1]],"filled":[[0,0]],"changed":[],"count":0}}]}},{"id":"all-water-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What does a grid with no land return?","summary":"Every cell in this grid is water.","workspacePanel":"visualizer","options":[{"id":"zero","label":"0","rationale":"The border flood finds no land to sink, and the interior sweep finds no land to count, so the counter never leaves 0.","isCorrect":true},{"id":"one","label":"1, the surrounding water counts as one region","rationale":"Water is never an island. Only land blobs are counted, and there are none here.","isCorrect":false},{"id":"cells","label":"The number of interior cells","rationale":"The count rises only when the interior sweep meets land. With no land anywhere, it stays at 0.","isCorrect":false}],"answer":"0. With no land to sink or count, both passes do nothing and the counter stays where it started.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-water-state","state":{"grid":[[1,1,1],[1,1,1]],"count":0}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the two passes into code","summary":"One four-direction flood does both jobs; only the starting cells change.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]],"count":0}}]},"body":["Write one flood that stops at the grid edge or at water and otherwise sinks the cell and steps to its four neighbors. Run it from every cell along all four borders to clear the open land. Then sweep the interior, and each land cell still standing is one more closed island to count and flood away."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the two passes","title":"Build the border flood and the count","summary":"Build the moves in order: flood border land, sweep the interior, flood each counted blob, and return the count.","workspacePanel":"code","checkpoints":[{"id":"border-flood","title":"Flood border-connected land","description":"Run DFS from border cells so any land touching the border is removed before counting.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_recursive_cell_exploration","scope":"call-dfs","readMode":"grid-recursive-search-value-query-v1"}]},"commonMistakes":["Counting border land as closed","Only checking the top and left borders"],"hint":"Call DFS from all four borders before scanning the interior.","semanticSpec":{"intent":"Start recursive grid exploration from grid cells before the closed-island count.","doneWhen":"The code invokes a DFS-style helper on grid coordinates.","shouldFailWhen":"This step should fail if no recursive cell exploration is started.","roles":["border cells","DFS helper"],"mustProve":["The solution starts recursive exploration from grid coordinates."],"mustNotAccept":["Counting cells without any connected-component traversal."]}},{"id":"dfs-base-case","title":"Stop DFS outside land","description":"Stop recursion when the cell is outside the grid or is not land.","validation":{"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"}]},"commonMistakes":["Reading grid cells before checking bounds","Letting DFS cross water"],"hint":"Check bounds before looking at `grid[r][c]`.","semanticSpec":{"intent":"Guard recursive grid exploration with boundary and cell-state checks.","doneWhen":"The DFS helper returns before exploring out-of-bounds cells.","shouldFailWhen":"This step should fail if the helper can recurse outside the grid.","roles":["boundary guard","cell-state guard"],"mustProve":["The recursive helper checks grid boundaries."],"mustNotAccept":["A DFS helper with no boundary guard."]}},{"id":"explore-neighbors","title":"Explore four neighbors","description":"From each land cell, recurse into its four orthogonal neighbors.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"explores_grid_neighbors","scope":"explore-neighbors","readMode":"grid-recursive-search-value-query-v1"}]},"commonMistakes":["Exploring only one direction","Using diagonal neighbors"],"hint":"Use up, down, left, and right moves.","semanticSpec":{"intent":"Traverse each connected land component by recursive neighbor exploration.","doneWhen":"DFS recurses to neighboring grid cells.","shouldFailWhen":"This step should fail if recursion does not move through grid neighbors.","roles":["neighbor cells","component traversal"],"mustProve":["The recursive helper explores adjacent grid coordinates."],"mustNotAccept":["Only checking the current cell."]}},{"id":"scan-interior","title":"Scan the remaining grid","description":"After the border flood, scan the grid for land components that remain.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops","readMode":"grid-enumeration-value-query-v1"}]},"commonMistakes":["Only scanning the border","Stopping after the first closed island"],"hint":"Use nested row and column loops for the counting pass.","semanticSpec":{"intent":"Enumerate grid cells to find remaining land components.","doneWhen":"The solution uses nested loops over grid rows and columns.","shouldFailWhen":"This step should fail if the counting pass does not traverse grid cells.","roles":["row loop","column loop","grid cells"],"mustProve":["The grid is scanned by row and column."],"mustNotAccept":["A single-cell check with no grid traversal."]}},{"id":"count-closed-island","title":"Return the closed-island count","description":"When an unvisited land cell remains, count one closed island, flood that component, and return the completed count.","validation":{"type":"semantic","validator":"all","params":[{"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"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_updated_zero_numeric_state","scope":"count-closed-island","readMode":"numeric-state-value-query-v1"}]}]},"commonMistakes":["Counting every land cell instead of each component","Forgetting to flood the counted component"],"hint":"Only increment when you find the first cell of a remaining land component, then DFS from it; return the count after the scan.","semanticSpec":{"intent":"Count closed components by gating DFS entry on remaining land.","doneWhen":"The code initializes a count, checks for a remaining land cell, increments once per component, starts DFS from that cell, and returns the completed count.","shouldFailWhen":"This step should fail if the count is not initialized or if DFS is not gated by a land check.","roles":["closed-island count","remaining land","component entry"],"mustProve":["The count starts from zero.","Component traversal starts only after a land-cell check.","The completed count is returned."],"mustNotAccept":["Counting water cells.","Incrementing without a component-entry gate."]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Erase the open land first, and every blob that remains is closed.","workspacePanel":"code","body":["Flooding from all four borders removes exactly the land that disqualifies an island. After it, the interior sweep counts survivors with no per-blob test, because surviving the border flood is the proof of closure.","Both passes share one four-direction flood; the only difference is where they start."],"takeaways":[{"title":"Eliminate, then count","body":"Sinking every border-reachable blob first turns the hard test \"does this blob touch an edge?\" into the easy test \"is there still land here?\"."},{"title":"All four borders, or none","body":"A blob can reach the edge from any side, so seeding the flood from only some borders lets open islands survive and inflates the count."},{"title":"Same flood, two roles","body":"The four-direction flood clears open land in the first pass and sinks counted islands in the second, so one helper does both jobs."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
