{"id":"number-of-enclaves","title":"Number of Enclaves","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"],"sizes":[9,25,64,144]},"description":"You are given an `m x n` binary matrix `grid`, where `0` is sea and `1` is land.\n\nA move consists of walking from one land cell to another 4-directionally adjacent land cell, or walking off the boundary of the grid.\n\nReturn the number of land cells in `grid` that cannot walk off the boundary in any number of moves.","examples":[{"input":"grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]","output":"3","explanation":"The three interior land cells are connected to each other but not to the boundary."},{"input":"grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]","output":"0","explanation":"Every land cell is connected to the boundary, so none are enclaves."},{"input":"grid = [[0,0,0],[0,1,0],[0,0,0]]","output":"1","explanation":"The center land cell cannot reach the boundary."}],"constraints":[{"id":"m-len-grid","text":"m == len(grid)"},{"id":"n-len-grid-i","text":"n == len(grid[i])"},{"id":"1-m-n-500","text":"1 <= m, n <= 500","check":[{"kind":"sizeRange","target":"grid","measure":"matrixRows","min":1,"max":500},{"kind":"valueRange","target":"grid","selector":"arrayItemLengths","min":1,"max":500}]},{"id":"grid-i-j-is-0-or-1","text":"grid[i][j] is 0 or 1","check":{"kind":"domain","target":"grid","selector":"nestedArrayItems","allowed":[0,1],"rectangular":true}}],"starterCode":"class Solution:\n    def numEnclaves(self, grid: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"numEnclaves","testCases":[{"id":"1","input":{"grid":[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]},"expected":3,"description":"Canonical case with three interior land cells."},{"id":"2","input":{"grid":[[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]},"expected":0,"description":"All land is connected to the boundary."},{"id":"3","input":{"grid":[[0,0,0],[0,1,0],[0,0,0]]},"expected":1,"description":"A single center enclave."},{"id":"4","input":{"grid":[[1,1,1],[1,1,1],[1,1,1]]},"expected":0,"description":"All-land grid is boundary-connected."},{"id":"5","input":{"grid":[[0,0,0,0,0],[0,1,0,1,0],[0,1,0,0,0],[0,0,0,1,0],[0,0,0,0,0]]},"expected":4,"description":"Multiple interior components contribute all their cells."},{"id":"6","input":{"grid":[[0,1,0,0,0],[0,1,1,1,0],[0,0,0,1,0],[0,1,1,1,0],[0,0,0,0,0]]},"expected":0,"description":"A winding land path touches the boundary, so it is not an enclave."},{"id":"h1","input":{"grid":[[0]]},"expected":0,"description":"Single sea cell."},{"id":"h2","input":{"grid":[[1]]},"expected":0,"description":"Single land cell is on the boundary."},{"id":"h3","input":{"grid":[[0,0,0,0],[0,1,1,0],[0,1,1,0],[0,0,0,0]]},"expected":4,"description":"A compact interior block."},{"id":"h4","input":{"grid":[[0,0,0,0,0],[0,1,0,1,0],[0,0,0,0,0]]},"expected":2,"description":"Two isolated interior land cells."},{"id":"topup-enclosed-block","input":{"grid":[[0,0,0,0],[0,1,1,0],[0,1,0,0],[0,0,0,0]]},"expected":3,"description":"Interior land cells that cannot reach the border are enclaves."},{"id":"topup-border-connected-land","input":{"grid":[[1,0,0],[1,1,0],[0,1,0]]},"expected":0,"description":"All land connected to the border is removed."}],"hints":[{"level":1,"content":"Any land cell connected to the boundary is not an enclave.","revealPattern":false},{"level":2,"content":"First remove all land reachable from the grid boundary, then count what remains.","revealPattern":true},{"level":3,"content":"Run DFS from all border land cells. After that flood-fill, every remaining `1` is an enclave cell.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"border-flood-fill","name":"Boundary DFS flood-fill","summary":"Mark land reachable from the boundary, then scan for land that was never reached.","decisionReason":"Any land cell connected to the boundary can walk off the grid, so flooding from boundary land removes exactly the non-enclave cells. The final scan counts the land cells that no boundary flood reached.","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Runs in O(m*n) time and uses O(m*n) space."],"isOptimal":true,"steps":["Define a DFS that stops at water or out-of-bounds cells.","Flood-fill land reachable from the top, bottom, left, and right borders.","Scan the grid for remaining land.","Use DFS return values to add the size of each remaining component."]},{"id":"scan-every-component-first","name":"Classify every component","summary":"Run DFS from every land component and track whether it touches the boundary.","decisionReason":"Classifying every land component returns the same enclave count in O(m*n) time. This flow removes boundary-connected land first so the final scan can count remaining cells directly.","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Runs in O(m*n) time and uses O(m*n) space."],"isViable":true,"isOptimal":false,"steps":["Start DFS from each unvisited land cell.","Track component size and whether it touches a border.","Add the component size only if it never touches a border."]}]},"codingCheckpoints":[{"id":"border-flood","title":"Flood boundary land","description":"Start DFS from the grid boundary so escapable land 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":["Only flooding one side of the border","Counting before removing boundary-connected land"],"hint":"Call DFS from rows on the left and right edges, then columns on the top and bottom edges.","semanticSpec":{"intent":"Start recursive grid exploration from boundary coordinates before counting enclaves.","doneWhen":"DFS-style exploration is invoked on grid coordinates before the final count.","shouldFailWhen":"The solution never starts a recursive cell exploration.","roles":["boundary cells","DFS helper"],"mustProve":["The solution starts recursive exploration from grid coordinates."],"mustNotAccept":["Counting cells without a flood-fill traversal."]}},{"id":"dfs-base-case","title":"Stop DFS outside land","description":"Return from DFS when the coordinate is out of bounds or 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 walk through sea cells"],"hint":"Check boundaries and land state before mutating the cell.","semanticSpec":{"intent":"Guard recursive exploration so invalid or sea cells stop immediately.","doneWhen":"The DFS helper returns before exploring out-of-bounds or non-land cells.","shouldFailWhen":"The helper can recurse outside the grid or through sea.","roles":["boundary guard","land check"],"mustProve":["The recursive helper checks grid boundaries before continuing."],"mustNotAccept":["A DFS helper with no boundary guard."]}},{"id":"explore-neighbors","title":"Explore four neighbors","description":"After marking a 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":["Using diagonal moves","Exploring only one or two directions"],"hint":"Use down, up, right, and left recursive calls.","semanticSpec":{"intent":"Traverse each connected land component through orthogonal neighbors.","doneWhen":"DFS recurses to adjacent grid coordinates.","shouldFailWhen":"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":"init-count","title":"Initialize enclave count","description":"Create a counter for the number of remaining land cells.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Starting from one","Reusing the row or column variable as the count"],"hint":"After the boundary flood, start a fresh count at zero.","semanticSpec":{"intent":"Initialize the numeric answer state before scanning remaining land.","doneWhen":"A dedicated count starts at zero before the final grid traversal.","shouldFailWhen":"The count is missing or starts nonzero.","roles":["enclave count","remaining land"],"mustProve":["The solution initializes a numeric count to zero."],"mustNotAccept":["Starting the answer count at a nonzero value."]}},{"id":"nested-loops","title":"Scan the remaining grid","description":"Use nested loops to inspect every cell after the boundary flood.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops","readMode":"grid-enumeration-value-query-v1"}]},"commonMistakes":["Scanning only the interior rows but missing columns","Stopping after the first enclave component"],"hint":"Every remaining land cell contributes to the answer.","semanticSpec":{"intent":"Enumerate the grid to find all land left after removing boundary-connected components.","doneWhen":"The solution uses nested row and column loops over grid cells.","shouldFailWhen":"The counting pass does not traverse grid cells.","roles":["row loop","column loop","grid cell"],"mustProve":["The grid is scanned by row and column."],"mustNotAccept":["A single-cell check with no grid traversal."]}},{"id":"count-enclaves","title":"Add each enclave component size","description":"When remaining land is found, add the DFS-returned component size to the 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":"array-scan","fact":"additively_updates_accumulator","scope":"update-total","readMode":"array-scan-value-query-v1"}]}]},"commonMistakes":["Counting components instead of cells","Adding cells before removing boundary-connected land"],"hint":"The DFS returns the size of a remaining component, so add that value to the running count.","semanticSpec":{"intent":"Gate the counting update on remaining land and accumulate the size of each remaining component.","doneWhen":"A land check guards an additive update to the enclave count.","shouldFailWhen":"The count updates unconditionally or only counts components.","roles":["remaining land cell","component-size DFS","enclave count"],"mustProve":["The count update happens only for remaining land.","The update adds a numeric component size."],"mustNotAccept":["Incrementing the answer for sea cells.","Returning the number of components instead of the number of enclave cells."]}},{"id":"return-count","title":"Return the enclave count","description":"Return the final numeric count after the scan finishes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Returning the grid","Returning the last component size instead of the total"],"hint":"Return the running count accumulated across all remaining land components.","semanticSpec":{"intent":"Return the accumulated numeric answer.","doneWhen":"The function returns the numeric count after all cells are scanned.","shouldFailWhen":"The function returns the grid, rows, columns, or a local component size.","roles":["enclave count","terminal return"],"mustProve":["The terminal return reads the accumulated numeric state."],"mustNotAccept":["Returning a non-answer state."]}}],"slides":[{"id":"read-the-problem","chapter":"The map","kind":"info","eyebrow":"Read the problem","title":"Count the land that cannot walk off the grid","workspacePanel":"problem","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"opener-state","state":{"grid":[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]],"count":0}}]},"body":["Each 1 is land and each 0 is sea. From a land cell you may step to a 4-directionally adjacent land cell, or walk off the edge of the grid. An enclave is a land cell that can never reach the edge no matter how it walks.","A land cell escapes if any chain of land neighbors reaches the edge, so a cell deep in the interior can still get out through a long corridor."]},{"id":"naive-escape-test","chapter":"The obvious way","kind":"code-trace","eyebrow":"Try the direct way","title":"For each blob, ask whether it can reach an edge","workspacePanel":"trace","summary":"The direct reading is to find each land blob, gather its cells, and walk it to see whether any cell touches the edge. Add the blob's size to the count only when the walk never escapes.","codeTrace":{"contract":"guided-code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def numEnclaves(grid: list[list[int]]) -> int:\n    rows = len(grid)\n    cols = len(grid[0])\n    esc = [False]\n\n    def dfs(r: int, c: int, esc: list[bool]) -> int:\n        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0:\n            return 0\n        grid[r][c] = 0\n        if r == 0 or r == rows - 1 or c == 0 or c == cols - 1:\n            esc[0] = True\n        return 1 + dfs(r + 1, c, esc) + dfs(r - 1, c, esc) + dfs(r, c + 1, esc) + dfs(r, c - 1, esc)\n    count = 0\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                esc[0] = False\n                size = dfs(r, c, esc)\n                if not esc[0]:\n                    count += size\n    return count","steps":[{"id":"find-border-blob","title":"The scan finds the left-edge land","codeLine":16,"summary":"The scan reaches the land at (1,0). It walks the blob and the walk immediately sees row 1 column 0 sits on the left edge, so this blob escapes and contributes nothing.","state":{"grid":[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]],"r":1,"c":0,"count":0}},{"id":"escapes","title":"That blob reaches the edge, so skip it","codeLine":17,"summary":"reaches_edge came back true for the (1,0) blob, so its single cell is not counted. The scan moves on, the count still 0.","state":{"grid":[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]],"r":1,"c":0,"filled":[[1,0]],"changed":[[1,0]],"count":0}},{"id":"interior-blob","title":"The scan finds the interior blob","codeLine":18,"summary":"At (1,2) the scan starts a fresh walk. It covers (1,2), (2,2), (2,1) and never touches an edge, so this blob is trapped and its 3 cells are added.","state":{"grid":[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]],"r":1,"c":2,"filled":[[1,2],[2,2],[2,1]],"changed":[[1,2],[2,2],[2,1]],"count":3}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const rows = grid.length;\nconst cols = grid[0].length;\nconst esc = [false];\nfunction dfs(r, c, esc) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === 0) {\n        return 0;\n    }\n    grid[r][c] = 0;\n    if (r === 0 || r === (rows - 1) || c === 0 || c === (cols - 1)) {\n        esc[0] = true;\n    }\n    return ((((1 + dfs((r + 1), c, esc)) + dfs((r - 1), c, esc)) + dfs(r, (c + 1), esc)) + dfs(r, (c - 1), esc));\n}\nlet count = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (grid[r][c] === 1) {\n            esc[0] = false;\n            const size = dfs(r, c, esc);\n            if (!esc[0]) {\n                count += size;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"2":1,"3":2,"4":3,"7":5,"8":6,"9":8,"10":9,"11":10,"12":12,"13":14,"14":15,"15":16,"16":17,"17":18,"18":19,"19":20,"20":21,"21":26},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":6,"endLine":7},"11":{"startLine":10,"endLine":11},"12":{"startLine":12,"endLine":13},"20":{"startLine":21,"endLine":25}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const rows = grid.length;\nconst cols = grid[0].length;\nconst esc = [false];\nfunction dfs(r: number, c: number, esc: Array<boolean>): number {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === 0) {\n        return 0;\n    }\n    grid[r][c] = 0;\n    if (r === 0 || r === (rows - 1) || c === 0 || c === (cols - 1)) {\n        esc[0] = true;\n    }\n    return ((((1 + dfs((r + 1), c, esc)) + dfs((r - 1), c, esc)) + dfs(r, (c + 1), esc)) + dfs(r, (c - 1), esc));\n}\nlet count = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (grid[r][c] === 1) {\n            esc[0] = false;\n            const size = dfs(r, c, esc);\n            if (!esc[0]) {\n                count += size;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"2":1,"3":2,"4":3,"7":5,"8":6,"9":8,"10":9,"11":10,"12":12,"13":14,"14":15,"15":16,"16":17,"17":18,"18":19,"19":20,"20":21,"21":26},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":6,"endLine":7},"11":{"startLine":10,"endLine":11},"12":{"startLine":12,"endLine":13},"20":{"startLine":21,"endLine":25}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int rows = grid.Count;\nint cols = grid[0].Count;\nList<bool> esc = new() { false };\nint Dfs(int r, int c, List<bool> esc) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == 0) {\n        return 0;\n    }\n    grid[r][c] = 0;\n    if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {\n        esc[0] = true;\n    }\n    return 1 + Dfs(r + 1, c, esc) + Dfs(r - 1, c, esc) + Dfs(r, c + 1, esc) + Dfs(r, c - 1, esc);\n    return 0;\n}\nint count = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (grid[r][c] == 1) {\n            esc[0] = false;\n            int size = Dfs(r, c, esc);\n            if (!esc[0]) {\n                count += size;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"2":1,"3":2,"4":3,"7":5,"8":6,"9":8,"10":9,"11":10,"12":12,"13":15,"14":16,"15":17,"16":18,"17":19,"18":20,"19":21,"20":22,"21":27},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":6,"endLine":7},"11":{"startLine":10,"endLine":11},"12":{"startLine":12,"endLine":14},"20":{"startLine":22,"endLine":26}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int, int, vector<bool>&)> dfs;\n\nint rows = grid.size();\nint cols = grid[0].size();\nvector<bool> esc{false};\ndfs = [&]( int r, int c, vector<bool>& esc ) -> int {\n    if (((((r < 0 || r >= rows) || c < 0) || c >= cols) || grid[r][c] == 0)) {\n        return 0;\n    }\n    grid[r][c] = 0;\n    if ((((r == 0 || r == (rows - 1)) || c == 0) || c == (cols - 1))) {\n        esc[0] = true;\n    }\n    return ((((1 + dfs((r + 1), c, esc)) + dfs((r - 1), c, esc)) + dfs(r, (c + 1), esc)) + dfs(r, (c - 1), esc));\n};\nint count = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (grid[r][c] == 1) {\n            esc[0] = false;\n            int size = dfs(r, c, esc);\n            if (!esc[0]) {\n                count += size;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"2":3,"3":4,"4":5,"7":7,"8":8,"9":10,"10":11,"11":12,"12":14,"13":16,"14":17,"15":18,"16":19,"17":20,"18":21,"19":22,"20":23,"21":28},"statementBundles":{"4":{"startLine":5,"endLine":6},"8":{"startLine":8,"endLine":9},"11":{"startLine":12,"endLine":13},"12":{"startLine":14,"endLine":15},"20":{"startLine":23,"endLine":27}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int dfs(int r, int c, List<Boolean> esc, int rows, int cols, List<List<Integer>> grid) {\n    if (((((r < 0 || r >= rows) || c < 0) || c >= cols) || grid.get(r).get(c) == 0)) {\n        return 0;\n    }\n    grid.get(r).set(c, 0);\n    if ((((r == 0 || r == (rows - 1)) || c == 0) || c == (cols - 1))) {\n        esc.set(0, true);\n    }\n    return ((((1 + dfs((r + 1), c, esc, rows, cols, grid)) + dfs((r - 1), c, esc, rows, cols, grid)) + dfs(r, (c + 1), esc, rows, cols, grid)) + dfs(r, (c - 1), esc, rows, cols, grid));\n}\n\nint rows = grid.size();\nint cols = grid.get(0).size();\nList<Boolean> esc = new ArrayList<>(List.of(false));\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) == 1) {\n            esc.set(0, false);\n            int size = dfs(r, c, esc, rows, cols, grid);\n            if (!esc.get(0)) {\n                count += size;\n            }\n        }\n    }\n}\nreturn count;","lineMap":{"2":12,"3":13,"4":14,"7":2,"8":3,"9":5,"10":6,"11":7,"12":9,"13":15,"14":16,"15":17,"16":18,"17":19,"18":20,"19":21,"20":22,"21":27},"statementBundles":{"8":{"startLine":3,"endLine":4},"11":{"startLine":7,"endLine":8},"12":{"startLine":9,"endLine":10},"20":{"startLine":22,"endLine":26}}}}}},{"id":"naive-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Weigh the cost","title":"What does the escape test force every blob's walk to carry?","summary":"Each blob has to be walked once to gather its cells and again, or alongside, to decide whether any of them escaped.","workspacePanel":"trace","options":[{"id":"thread-verdict","label":"An escape verdict that has to ride through every recursive return before the blob's size can be trusted","rationale":"The walk only knows the blob is trapped after it has covered every cell and no branch reported an edge. The verdict has to combine through each recursive return, and one dropped return on one branch turns a trapped blob into an escaped one or the reverse.","isCorrect":true},{"id":"stop-at-edge","label":"Nothing extra; stop the walk the moment a cell touches the edge","rationale":"Stopping early leaves the rest of the blob unmarked, so the scan re-enters it and walks it again. The walk cannot quit until the whole blob is covered.","isCorrect":false},{"id":"first-cell","label":"Just the first cell's position, which already says whether the blob escapes","rationale":"One cell cannot tell you whether the blob reaches an edge somewhere else. Escaping is a property of the whole connected shape.","isCorrect":false}],"answer":"Every blob still costs an O(rows*cols) walk, but each walk also has to thread an escape verdict through every recursive return and only trust the blob's size once the whole shape is covered. That per-blob verdict is fragile bookkeeping: one missed return and a blob is counted on the wrong side."},{"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 escape test?","summary":"The baseline threaded an escape verdict because any blob might reach an edge. What if every escaping cell were already gone before the count began?","workspacePanel":"visualizer","options":[{"id":"remaining-trapped","label":"Sink every cell reachable from the border first, and every land cell still standing is an enclave","rationale":"Escaping means reachable from the edge. A flood from every border cell sinks exactly that land, so whatever land remains was never reachable from an edge. The enclave test becomes \"is there still land here?\".","isCorrect":true},{"id":"lose-enclaves","label":"You would also sink the enclaves, leaving nothing to count","rationale":"An enclave is unreachable from the border by definition, so a flood that starts only at border cells can never reach it. Only the escaping land disappears.","isCorrect":false},{"id":"still-verdict","label":"You would still need the escape verdict on the second pass","rationale":"Once the escaping land is gone, every leftover land cell is guaranteed trapped. There is nothing left to test, so the verdict is no longer needed.","isCorrect":false}],"answer":"Flood from every border cell first. That sinks all the escaping land, so every land cell that survives is an enclave and you just count the survivors, no per-blob verdict required.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-flip-state","state":{"grid":[[0,0,0,0],[0,0,1,0],[0,1,1,0],[0,0,0,0]],"filled":[[1,0]],"changed":[],"count":0}}]}},{"id":"count-cells","chapter":"The trick","kind":"info","eyebrow":"Hold the idea","title":"Sink the escaping land, then count every survivor cell","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"count-cells-state","state":{"grid":[[0,0,0,0],[0,0,1,0],[0,1,1,0],[0,0,0,0]],"filled":[[1,2],[2,2],[2,1]],"changed":[],"count":3}}]},"body":["The first pass floods from every border cell, sinking all the land an edge walk could reach. In the sample that removes only (1,0), the lone escaping cell.","The second pass sweeps the interior. The three survivors (1,2), (2,2), (2,1) form one blob but contribute 3 cells to the answer, so the sweep adds the size of each surviving blob."]},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Border flood first, then total the survivors","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-setup-state","state":{"grid":[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,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 remaining cells. On sea it keeps moving; on land it measures the whole surviving blob, adds that many to the count, and sinks the blob so the sweep never meets it twice."]},{"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":[[0,0,0,0],[0,0,1,0],[0,1,1,0],[0,0,0,0]],"filled":[[1,0]],"changed":[[1,0]],"count":0}},{"id":"measure-blob","state":{"grid":[[0,0,0,0],[0,0,1,0],[0,1,1,0],[0,0,0,0]],"r":1,"c":2,"filled":[[1,0]],"changed":[],"count":0}},{"id":"final","state":{"grid":[[0,0,0,0],[1,0,0,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":2,"filled":[[1,0],[1,2],[2,2],[2,1]],"changed":[[1,2],[2,2],[2,1]],"count":3}}]},"beats":[{"id":"after-border-flood","title":"After the border flood, which land is still standing?","summary":"Every flood started from a border cell and sank what it could reach.","prompt":"The four borders have all been flooded.","options":[{"id":"interior-three","label":"The three cells (1,2), (2,2), (2,1)","rationale":"The only border-reaching land was (1,0), and the border flood sank it. The three interior cells sit behind sea on every side, so no flood reached them and they survive.","isCorrect":true},{"id":"none","label":"No land at all","rationale":"The interior blob is unreachable from any border, so no flood could touch it. Three land cells are still standing.","isCorrect":false},{"id":"all-of-it","label":"All the original land, since flooding only marks","rationale":"The border flood does not just mark, it sinks (1,0) to sea. The escaping cell is gone; only the trapped three remain.","isCorrect":false}],"answer":"The three interior cells survive. (1,0) was reachable from the left edge, so the border flood sank it, leaving only the trapped blob."},{"id":"measure-blob","title":"The sweep reaches the first survivor at (1,2). What does it add to the count?","summary":"The interior sweep finds land at (1,2), and the count is still 0.","prompt":"The sweep lands on a survivor of the border flood.","options":[{"id":"size-three","label":"The whole blob's size, 3","rationale":"Any land left after the border flood is trapped, and the answer counts cells. Measuring this blob covers (1,2), (2,2), (2,1), so 3 is added at once and the blob is sunk to avoid re-counting.","isCorrect":true},{"id":"one","label":"Just 1, then move on to find the rest","rationale":"Adding 1 per blob would undercount this case. The three connected survivors are one blob but three enclave cells, so the sweep must add the blob's full size.","isCorrect":false},{"id":"retest","label":"Nothing yet; first walk it to confirm it never escapes","rationale":"The border flood already removed everything that escapes, so a survivor cannot reach an edge. No further escape test is needed.","isCorrect":false}],"answer":"Add 3, the whole blob's size. A survivor is trapped by construction, and because the answer counts cells the sweep adds every cell of the blob, then sinks it."},{"id":"final","title":"One blob has been totalled. What does the rest of the sweep find?","summary":"The interior blob has been measured and sunk, and the count holds 3.","prompt":"The sweep continues past the counted blob toward the end of the grid.","options":[{"id":"nothing-more","label":"Nothing more, so it returns 3","rationale":"Every other cell the sweep meets is sea, either original or sunk by a flood, so no new blob starts. The count stays at 3 and that value is returned.","isCorrect":true},{"id":"recount","label":"It re-enters the same blob and adds 3 again","rationale":"The blob was sunk the moment it was measured, so the sweep now reads those cells as sea and never re-enters them. They are counted exactly once.","isCorrect":false},{"id":"find-more","label":"It finds another enclave blob in the leftover grid","rationale":"Only one blob survived the border flood. Every remaining cell is sea, so there is no second blob to total.","isCorrect":false}],"answer":"Nothing more. The rest of the grid is sea, so no new blob starts and the sweep returns the 3 it already holds."}]},{"id":"count-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Is flooding the top and bottom rows enough?","workspacePanel":"trace","summary":"The whole approach rests on sinking every cell an edge walk could reach before counting. It is easy to seed the flood from the top and bottom rows and forget the left and right columns. On grids whose only escaping land touches the top or bottom that even gives the right total. Watch it on land that escapes through a side edge.","pitfall":"The flood below seeds only the top and bottom rows, so land that reaches the grid only through the left or right column is never sunk and gets counted as an enclave.","whyItMatters":"A land cell escapes if it can reach any edge, and the left and right columns are edges too. Land that touches only a side column is escaping land, but a flood that skips those columns leaves it standing, so the sweep counts it as trapped. Here a two-cell column on the left edge should escape and contribute 0, yet the buggy flood reports 2. Seed the flood from all four borders: the left and right columns as well as the top and bottom rows.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def numEnclaves(grid: list[list[int]]) -> int:\n    rows = len(grid)\n    cols = len(grid[0])\n\n    def dfs(r: int, c: int) -> int:\n        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0:\n            return 0\n        grid[r][c] = 0\n        return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1)\n    for c in range(cols):\n        dfs(0, c)\n        dfs(rows - 1, c)\n    count = 0\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                count += dfs(r, c)\n    return count","steps":[{"id":"border-done","title":"The top-and-bottom flood sinks nothing","codeLine":9,"summary":"grid holds a two-cell land column at (1,0) and (2,0), sitting on the left edge. The flood seeds only row 0 and row 3, which are all sea, so it sinks nothing and the left-edge column survives into the count.","state":{"grid":[[0,0,0,0],[1,0,0,0],[1,0,0,0],[0,0,0,0]],"count":0}},{"id":"add-escaping","title":"The sweep counts the left-edge column","codeLine":17,"summary":"At (1,0) the sweep meets the surviving column, measures it as size 2, and adds 2 to the count. This column touches the left edge, so it escapes and should have been sunk before counting.","state":{"grid":[[0,0,0,0],[1,0,0,0],[1,0,0,0],[0,0,0,0]],"r":1,"c":0,"filled":[[1,0],[2,0]],"changed":[[1,0],[2,0]],"count":2}},{"id":"wrong-total","title":"It returns 2 for land that escapes","codeLine":18,"summary":"Every land cell here reaches the left edge, so the real answer is 0. By skipping the side columns the flood left that escaping land standing, and the function returns 2.","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":3,"c":3,"filled":[[1,0],[2,0]],"changed":[],"count":2}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const rows = grid.length;\nconst cols = grid[0].length;\nfunction dfs(r, c) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === 0) {\n        return 0;\n    }\n    grid[r][c] = 0;\n    return ((((1 + dfs((r + 1), c)) + dfs((r - 1), c)) + dfs(r, (c + 1))) + dfs(r, (c - 1)));\n}\nfor (let c = 0; c < cols; c++) {\n    dfs(0, c);\n    dfs((rows - 1), c);\n}\nlet count = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (grid[r][c] === 1) {\n            count += dfs(r, c);\n        }\n    }\n}\nreturn count;","lineMap":{"2":1,"3":2,"6":4,"7":5,"8":7,"9":8,"10":10,"11":11,"12":12,"13":14,"14":15,"15":16,"16":17,"17":18,"18":22},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":5,"endLine":6},"9":{"startLine":8,"endLine":9},"12":{"startLine":12,"endLine":13},"17":{"startLine":18,"endLine":21}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const rows = grid.length;\nconst cols = grid[0].length;\nfunction dfs(r: number, c: number): number {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === 0) {\n        return 0;\n    }\n    grid[r][c] = 0;\n    return ((((1 + dfs((r + 1), c)) + dfs((r - 1), c)) + dfs(r, (c + 1))) + dfs(r, (c - 1)));\n}\nfor (let c = 0; c < cols; c++) {\n    dfs(0, c);\n    dfs((rows - 1), c);\n}\nlet count = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (grid[r][c] === 1) {\n            count += dfs(r, c);\n        }\n    }\n}\nreturn count;","lineMap":{"2":1,"3":2,"6":4,"7":5,"8":7,"9":8,"10":10,"11":11,"12":12,"13":14,"14":15,"15":16,"16":17,"17":18,"18":22},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":5,"endLine":6},"9":{"startLine":8,"endLine":9},"12":{"startLine":12,"endLine":13},"17":{"startLine":18,"endLine":21}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int rows = grid.Count;\nint cols = grid[0].Count;\nint Dfs(int r, int c) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == 0) {\n        return 0;\n    }\n    grid[r][c] = 0;\n    return 1 + Dfs(r + 1, c) + Dfs(r - 1, c) + Dfs(r, c + 1) + Dfs(r, c - 1);\n    return 0;\n}\nfor (int c = 0; c < cols; c++) {\n    Dfs(0, c);\n    Dfs(rows - 1, c);\n}\nint count = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (grid[r][c] == 1) {\n            count += Dfs(r, c);\n        }\n    }\n}\nreturn count;","lineMap":{"2":1,"3":2,"6":4,"7":5,"8":7,"9":8,"10":11,"11":12,"12":13,"13":15,"14":16,"15":17,"16":18,"17":19,"18":23},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":5,"endLine":6},"9":{"startLine":8,"endLine":10},"12":{"startLine":13,"endLine":14},"17":{"startLine":19,"endLine":22}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int, int)> dfs;\n\nint rows = grid.size();\nint cols = grid[0].size();\ndfs = [&]( int r, int c ) -> int {\n    if (((((r < 0 || r >= rows) || c < 0) || c >= cols) || grid[r][c] == 0)) {\n        return 0;\n    }\n    grid[r][c] = 0;\n    return ((((1 + dfs((r + 1), c)) + dfs((r - 1), c)) + dfs(r, (c + 1))) + dfs(r, (c - 1)));\n};\nfor (int c = 0; c < cols; c++) {\n    dfs(0, c);\n    dfs((rows - 1), c);\n}\nint count = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (grid[r][c] == 1) {\n            count += dfs(r, c);\n        }\n    }\n}\nreturn count;","lineMap":{"2":3,"3":4,"6":6,"7":7,"8":9,"9":10,"10":12,"11":13,"12":14,"13":16,"14":17,"15":18,"16":19,"17":20,"18":24},"statementBundles":{"3":{"startLine":4,"endLine":5},"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":11},"12":{"startLine":14,"endLine":15},"17":{"startLine":20,"endLine":23}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int 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) == 0)) {\n        return 0;\n    }\n    grid.get(r).set(c, 0);\n    return ((((1 + dfs((r + 1), c, rows, cols, grid)) + dfs((r - 1), c, rows, cols, grid)) + dfs(r, (c + 1), rows, cols, grid)) + dfs(r, (c - 1), rows, cols, grid));\n}\n\nint rows = grid.size();\nint cols = grid.get(0).size();\nfor (int c = 0; c < cols; c++) {\n    dfs(0, c, rows, cols, grid);\n    dfs((rows - 1), c, rows, cols, grid);\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) == 1) {\n            count += dfs(r, c, rows, cols, grid);\n        }\n    }\n}\nreturn count;","lineMap":{"2":9,"3":10,"6":2,"7":3,"8":5,"9":6,"10":11,"11":12,"12":13,"13":15,"14":16,"15":17,"16":18,"17":19,"18":23},"statementBundles":{"7":{"startLine":3,"endLine":4},"9":{"startLine":6,"endLine":7},"12":{"startLine":13,"endLine":14},"17":{"startLine":19,"endLine":22}}}}}},{"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,0,0,0],[0,1,0,1,0],[0,1,0,0,0],[0,0,0,1,0],[0,0,0,0,0]],"count":0}}]},"body":["Flooding all four borders and then totalling the survivors handled the sample. Now push the same two passes against inputs the sample never exercised.","Two shapes are worth running before you code: a single-cell grid that is all land, and several separate enclave blobs in one grid."]},{"id":"single-cell-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"A 1x1 grid holding a single land cell returns what?","summary":"The whole grid is one land cell at (0,0).","workspacePanel":"visualizer","options":[{"id":"zero","label":"0, because that cell is on the border","rationale":"In a 1x1 grid the only cell sits on every edge at once, so the border flood sinks it before the count begins. No survivor is left, so the answer is 0.","isCorrect":true},{"id":"one","label":"1, since it is trapped land","rationale":"The single cell is on the boundary, so it walks straight off the edge. The border flood removes it and nothing remains to count.","isCorrect":false},{"id":"crash","label":"It cannot be handled without a special case","rationale":"The same border flood seeds row 0 and column 0, which is this cell, so it is sunk like any other edge land. No special case is needed.","isCorrect":false}],"answer":"0. The lone cell is on the boundary, so the border flood sinks it and the survivor count stays at 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-cell-state","state":{"grid":[[1]],"count":0}}]}},{"id":"multiple-blobs-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What total do three separate enclave blobs contribute?","summary":"After the border flood, three trapped blobs survive: a two-cell column at (1,1)-(2,1), and single cells at (1,3) and (3,3).","workspacePanel":"visualizer","options":[{"id":"four","label":"4, the sum of every survivor blob's cells","rationale":"The answer is total trapped cells, so the sweep adds each blob's size: 2 from the column plus 1 plus 1. Summing sizes across all blobs gives 4.","isCorrect":true},{"id":"three","label":"3, one per surviving blob","rationale":"That counts one per blob. The two-cell column is one blob but two enclave cells, so a per-blob count undercounts it by one.","isCorrect":false},{"id":"two","label":"2, the size of the largest blob","rationale":"The single cells at (1,3) and (3,3) are enclaves too, so counting only the biggest blob misses two cells.","isCorrect":false}],"answer":"4. Each surviving blob contributes its full size: 2 from the column and 1 from each single cell.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"multiple-blobs-state","state":{"grid":[[0,0,0,0,0],[0,1,0,1,0],[0,1,0,0,0],[0,0,0,1,0],[0,0,0,0,0]],"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, and the second pass adds the size it returns.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]],"count":0}}]},"body":["Write one flood that stops at the grid edge or at sea and otherwise sinks the cell, returns its own cell, and steps to its four neighbors, totalling what they return. Run it from every cell along all four borders to clear the escaping land. Then sweep the interior, and for each land cell still standing add the size that flood reports before moving on."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the two passes","title":"Build the border flood and the cell count","summary":"Time to build the two passes: the border flood that sinks every cell an edge can reach, then the sweep that totals what is left standing.","workspacePanel":"code","checkpoints":[{"id":"border-flood","title":"Flood boundary land","description":"Start DFS from the grid boundary so escapable land 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":["Only flooding one side of the border","Counting before removing boundary-connected land"],"hint":"Call DFS from rows on the left and right edges, then columns on the top and bottom edges.","semanticSpec":{"intent":"Start recursive grid exploration from boundary coordinates before counting enclaves.","doneWhen":"DFS-style exploration is invoked on grid coordinates before the final count.","shouldFailWhen":"The solution never starts a recursive cell exploration.","roles":["boundary cells","DFS helper"],"mustProve":["The solution starts recursive exploration from grid coordinates."],"mustNotAccept":["Counting cells without a flood-fill traversal."]}},{"id":"dfs-base-case","title":"Stop DFS outside land","description":"Return from DFS when the coordinate is out of bounds or 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 walk through sea cells"],"hint":"Check boundaries and land state before mutating the cell.","semanticSpec":{"intent":"Guard recursive exploration so invalid or sea cells stop immediately.","doneWhen":"The DFS helper returns before exploring out-of-bounds or non-land cells.","shouldFailWhen":"The helper can recurse outside the grid or through sea.","roles":["boundary guard","land check"],"mustProve":["The recursive helper checks grid boundaries before continuing."],"mustNotAccept":["A DFS helper with no boundary guard."]}},{"id":"explore-neighbors","title":"Explore four neighbors","description":"After marking a 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":["Using diagonal moves","Exploring only one or two directions"],"hint":"Use down, up, right, and left recursive calls.","semanticSpec":{"intent":"Traverse each connected land component through orthogonal neighbors.","doneWhen":"DFS recurses to adjacent grid coordinates.","shouldFailWhen":"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":"init-count","title":"Initialize enclave count","description":"Create a counter for the number of remaining land cells.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Starting from one","Reusing the row or column variable as the count"],"hint":"After the boundary flood, start a fresh count at zero.","semanticSpec":{"intent":"Initialize the numeric answer state before scanning remaining land.","doneWhen":"A dedicated count starts at zero before the final grid traversal.","shouldFailWhen":"The count is missing or starts nonzero.","roles":["enclave count","remaining land"],"mustProve":["The solution initializes a numeric count to zero."],"mustNotAccept":["Starting the answer count at a nonzero value."]}},{"id":"nested-loops","title":"Scan the remaining grid","description":"Use nested loops to inspect every cell after the boundary flood.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops","readMode":"grid-enumeration-value-query-v1"}]},"commonMistakes":["Scanning only the interior rows but missing columns","Stopping after the first enclave component"],"hint":"Every remaining land cell contributes to the answer.","semanticSpec":{"intent":"Enumerate the grid to find all land left after removing boundary-connected components.","doneWhen":"The solution uses nested row and column loops over grid cells.","shouldFailWhen":"The counting pass does not traverse grid cells.","roles":["row loop","column loop","grid cell"],"mustProve":["The grid is scanned by row and column."],"mustNotAccept":["A single-cell check with no grid traversal."]}},{"id":"count-enclaves","title":"Add each enclave component size","description":"When remaining land is found, add the DFS-returned component size to the 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":"array-scan","fact":"additively_updates_accumulator","scope":"update-total","readMode":"array-scan-value-query-v1"}]}]},"commonMistakes":["Counting components instead of cells","Adding cells before removing boundary-connected land"],"hint":"The DFS returns the size of a remaining component, so add that value to the running count.","semanticSpec":{"intent":"Gate the counting update on remaining land and accumulate the size of each remaining component.","doneWhen":"A land check guards an additive update to the enclave count.","shouldFailWhen":"The count updates unconditionally or only counts components.","roles":["remaining land cell","component-size DFS","enclave count"],"mustProve":["The count update happens only for remaining land.","The update adds a numeric component size."],"mustNotAccept":["Incrementing the answer for sea cells.","Returning the number of components instead of the number of enclave cells."]}},{"id":"return-count","title":"Return the enclave count","description":"Return the final numeric count after the scan finishes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Returning the grid","Returning the last component size instead of the total"],"hint":"Return the running count accumulated across all remaining land components.","semanticSpec":{"intent":"Return the accumulated numeric answer.","doneWhen":"The function returns the numeric count after all cells are scanned.","shouldFailWhen":"The function returns the grid, rows, columns, or a local component size.","roles":["enclave count","terminal return"],"mustProve":["The terminal return reads the accumulated numeric state."],"mustNotAccept":["Returning a non-answer state."]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Sink the escaping land first, then total every cell that remains.","workspacePanel":"code","body":["Flooding from all four borders removes exactly the land that can walk off the edge. After it, the interior sweep totals the survivors with no per-blob escape test, because surviving the border flood is the proof a cell is trapped.","The answer counts cells. The sweep adds the size each flood returns, so a 2x2 enclave contributes four cells even though it is one blob."],"takeaways":[{"title":"Eliminate, then count","body":"Sinking every border-reachable cell first turns the hard test \"can this blob walk off the edge?\" into the easy test \"is there still land here?\"."},{"title":"Count every trapped cell","body":"The answer is the number of trapped land cells, so each survivor blob adds its full size; a flat +1 per blob undercounts every blob bigger than one cell."},{"title":"Same flood, two roles","body":"The four-direction flood that returns a cell count clears escaping land in the first pass and measures-and-sinks each enclave 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"},"complexity":{"time":"O(m*n)","space":"O(m*n)","explanation":"Each cell is visited at most a constant number of times. The recursion stack can hold O(m*n) cells in the worst case."}}
