{"id":"max-area-of-island","title":"Max Area of Island","difficulty":"medium","patterns":["graph-dfs"],"primaryConcept":"graph-grid-fill","concepts":["graph-grid-fill","graph-components"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"grid","sizeMetric":"matrix-cells","constraints":["binary-int","connected-components"],"sizes":[9,25,64,144]},"description":"Given an `m x n` binary grid, return the maximum area of an island.\n\nAn island is a group of `1` cells connected 4-directionally. The area of an island is the number of cells in that connected group. Return `0` if the grid contains no land.","examples":[{"input":"grid = [[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]]","output":"5","explanation":"The plus-shaped island has 5 connected land cells."},{"input":"grid = [[0,0,0],[0,0,0]]","output":"0","explanation":"There is no land, so the largest island area is 0."},{"input":"grid = [[1,1],[1,1]]","output":"4","explanation":"All land cells are connected into one island."}],"constraints":[{"id":"m-len-grid","text":"m == len(grid)"},{"id":"n-len-grid-i","text":"n == len(grid[i])"},{"id":"1-m-n-50","text":"1 <= m, n <= 50","check":[{"kind":"sizeRange","target":"grid","measure":"matrixRows","min":1,"max":50},{"kind":"valueRange","target":"grid","selector":"arrayItemLengths","min":1,"max":50}]},{"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 maxAreaOfIsland(self, grid: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"maxAreaOfIsland","testCases":[{"id":"1","input":{"grid":[[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]]},"expected":5,"description":"One plus-shaped island."},{"id":"2","input":{"grid":[[0,0,0],[0,0,0]]},"expected":0,"description":"No land."},{"id":"3","input":{"grid":[[1,1],[1,1]]},"expected":4,"description":"All land is one island."},{"id":"4","input":{"grid":[[1,0,1],[0,1,0],[1,0,1]]},"expected":1,"description":"Diagonal land is not connected."},{"id":"5","input":{"grid":[[1,1,0,0,0],[1,0,0,1,1],[0,0,1,1,1],[0,0,0,1,0]]},"expected":6,"description":"Later island is larger than the first island."},{"id":"h1","input":{"grid":[[1]]},"expected":1,"description":"Single land cell."},{"id":"h2","input":{"grid":[[0]]},"expected":0,"description":"Single water cell."},{"id":"h3","input":{"grid":[[1,1,1,0],[0,0,1,0],[1,1,1,0]]},"expected":7,"description":"Bent connected island."},{"id":"h4","input":{"grid":[[1,1,1],[1,0,1],[1,1,1]]},"expected":8,"description":"A hole in the middle does not break connectivity."},{"id":"h5","input":{"grid":[[0,1,0,1],[1,1,0,1],[0,1,0,0]]},"expected":4,"description":"A smaller island can still beat isolated singletons."},{"id":"single-column-separated-islands","input":{"grid":[[1],[1],[0],[1]]},"expected":2,"description":"A single-column grid can contain separated vertical islands."},{"id":"right-side-bent-island","input":{"grid":[[1,0,1,1],[1,0,0,1],[0,0,1,1]]},"expected":5,"description":"The largest island can bend around gaps on the right side."}],"hints":[{"level":1,"content":"When you find a land cell, how can you measure the whole connected region before moving on?","revealPattern":false},{"level":2,"content":"Use DFS from each unvisited land cell. The DFS can `return` the number of cells it consumes.","revealPattern":true},{"level":3,"content":"Mark visited land by changing `1` to `0`, then add 1 plus the four recursive neighbor areas.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"max-area-of-island-2026-07-19-approach-before-search","approachSelection":{"contract":"approach-selection-v1","question":"Which way of measuring an island should we build?","decisionPrompt":"Choose the approach whose state and cost match the constraints.","approaches":[{"id":"dfs-area","name":"Sink each island and let the search report its size","summary":"Scan for fresh land, run one search that sinks the whole island and returns how many cells it consumed, and keep the largest size returned.","decisionReason":"Sinking each cell as it is counted means every cell is visited once, so the whole grid is measured in a single linear pass.","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Visits each cell once: O(m*n) time, O(m*n) recursion space."],"isOptimal":true},{"id":"restart-counts","name":"Re-measure from every land cell without marking","summary":"From every land cell, run a fresh search over its region, never marking cells as seen, and keep the largest size found.","decisionReason":"Without marking, a cell in a k-cell island is re-explored from each of those k cells, so one island is measured k times over: quadratic in the grid size.","complexity":{"time":"O((m*n)^2)","space":"O(m*n)"},"tradeoffs":["Re-walks each island from every one of its cells: O((m*n)^2) time."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-best-area","title":"Start the best area at zero","description":"Hold the largest island area found so far in one numeric state.","commonMistakes":["Starting from 1 even when the grid might hold no land","Seeding the answer with the grid dimensions"],"hint":"Before any land is found, the largest area known is zero.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count"}]},"semanticSpec":{"intent":"Initialize the best-area numeric state before scanning the grid.","doneWhen":"A numeric answer state starts at 0 before any island is measured.","roles":["best area","answer state"],"mustProve":["A numeric state for the answer is initialized to zero."],"mustNotAccept":["A nonzero initial answer."],"equivalentVariants":["Any named accumulator seeded to zero before the scan begins."],"proofSnippets":[{"id":"py-max-area-init-best","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0"}]}},{"id":"scan-grid","title":"Visit every cell of the grid","description":"Walk every row and column so no island start is missed.","commonMistakes":["Stopping before the last row or column","Walking only one dimension"],"hint":"Any cell could be the first fresh land of a new island.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops"}]},"semanticSpec":{"intent":"Visit every grid coordinate as a candidate island start.","doneWhen":"A two-level traversal covers every cell of the matrix.","roles":["row index","column index","grid cell"],"mustProve":["The traversal reaches each row and each column."],"mustNotAccept":["A scan that cannot reach every cell."],"equivalentVariants":["Any full-matrix scan that exposes every cell to the land check."],"proofSnippets":[{"id":"py-max-area-scan-grid","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    for r in range(len(grid)):\n        for c in range(len(grid[0])):\n            cell = grid[r][c]"}]}},{"id":"check-land","title":"Measure only from fresh land","description":"Begin a search only when the current cell is land that has not been sunk yet.","commonMistakes":["Searching from water","Re-entering land a previous search already sank"],"hint":"The search should begin only when the cell is land.","validation":{"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"}]},"semanticSpec":{"intent":"Gate the island measurement on a fresh land cell.","doneWhen":"The search entry runs only for a cell whose value is land.","roles":["fresh land","component entry"],"mustProve":["The current cell is compared with the land value before the search begins."],"mustNotAccept":["An unconditional search from every cell."],"equivalentVariants":["Any branch that treats only unsunk land as a new island start."],"proofSnippets":[{"id":"py-max-area-check-land","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    for r in range(len(grid)):\n        for c in range(len(grid[0])):\n            if grid[r][c] == 1:\n                best = max(best, 1)"}]}},{"id":"dfs-base-case","title":"Stop the search at water and the edge","description":"Return 0 when the search steps off the grid or onto water.","commonMistakes":["Reading the cell before checking the bounds","Returning area for a water cell"],"hint":"A step off the grid or onto water adds no area.","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"}]},"semanticSpec":{"intent":"Keep the search inside the grid and only on land.","doneWhen":"The search returns 0 before any change when the cell is out of bounds or water.","roles":["boundary guard","water guard","zero area"],"mustProve":["Bounds and water checks guard the recursion."],"mustNotAccept":["Recursing through water or off the grid."],"equivalentVariants":["Any guard that returns zero area before stepping into an invalid cell."],"proofSnippets":[{"id":"py-max-area-dfs-base-case","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    rows, cols = len(grid), 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        return 1\n\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                best = max(best, 1)"}]}},{"id":"explore-neighbors","title":"Sum the four neighbor areas","description":"Sink the current cell, then add the areas the four cardinal neighbors report back.","commonMistakes":["Leaving out one direction","Stepping to diagonal cells"],"hint":"A region is one for this cell plus the areas its four neighbors return.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"explores_grid_neighbors","scope":"explore-neighbors","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Accumulate all four-directionally connected land into the region area.","doneWhen":"The search adds the areas from the up, down, left, and right neighbors.","roles":["current cell","cardinal neighbors","recursive area"],"mustProve":["Recursive calls move to neighboring grid coordinates.","The helper returns the area accumulator that received those neighbor areas."],"mustNotAccept":["Only one direction, or diagonal movement.","Returning a constant or coordinate instead of the accumulated area."],"equivalentVariants":["Any sum of the four cardinal neighbor searches."],"proofSnippets":[{"id":"py-max-area-explore-neighbors","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    rows, cols = len(grid), 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        area = 1\n        area += dfs(r + 1, c)\n        area += dfs(r - 1, c)\n        area += dfs(r, c + 1)\n        area += dfs(r, c - 1)\n        return area\n\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                best = max(best, 1)"}]}},{"id":"update-best-area","title":"Keep the larger of best and this area","description":"Run the search from the fresh land cell and fold its returned area into the best area with a maximum.","commonMistakes":["Overwriting the best area with the latest island area","Adding the island areas together instead of taking the largest"],"hint":"After a search finishes, the best area is the larger of itself and the area just returned.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_recursive_cell_exploration","scope":"call-dfs","readMode":"grid-recursive-search-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best"}]}]},"semanticSpec":{"intent":"Measure one island and keep the larger of the previous best and this area.","doneWhen":"The search result is compared against the best area and the best state keeps the larger value.","roles":["current area","best area","maximum update"],"mustProve":["The returned island area flows into a maximum update of the best state."],"mustNotAccept":["Overwriting the best area with the last island, or summing the islands."],"equivalentVariants":["Any maximum that folds the returned area into the best state."],"proofSnippets":[{"id":"py-max-area-update-best","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    rows, cols = len(grid), 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        area = 1\n        area += dfs(r + 1, c)\n        area += dfs(r - 1, c)\n        area += dfs(r, c + 1)\n        area += dfs(r, c - 1)\n        return area\n\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                best = max(best, dfs(r, c))"}]}},{"id":"return-best-area","title":"Return the best area","description":"After the whole grid is scanned, return the largest area state.","commonMistakes":["Returning the grid","Returning the last island area instead of the largest"],"hint":"Return the best-area state after the scan finishes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_extremum_numeric_state","scope":"return-profit"}]},"semanticSpec":{"intent":"Return the maximum-area state after every island is measured.","doneWhen":"The final return is the same numeric state updated by the maximum.","roles":["best area","answer"],"mustProve":["The returned numeric state is the tracked maximum."],"mustNotAccept":["Returning grid dimensions or the sunk grid."],"equivalentVariants":["Return the same accumulator the maximum updates."],"proofSnippets":[{"id":"py-max-area-return-best","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    rows, cols = len(grid), 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        area = 1\n        area += dfs(r + 1, c)\n        area += dfs(r - 1, c)\n        area += dfs(r, c + 1)\n        area += dfs(r, c - 1)\n        return area\n\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                best = max(best, dfs(r, c))\n    return best"}]}}],"slides":[{"id":"read-the-signal","chapter":"The map","kind":"info","eyebrow":"Read the problem","title":"Measure the largest island","workspacePanel":"problem","body":["You get a grid of land (1) and water (0). An island is a group of land cells joined edge to edge, up, down, left, or right. Its area is how many cells it covers, and the job is to return the area of the biggest one.","Diagonal touches do not join cells. The whole question is the size of the biggest connected group."]},{"id":"one-island-many-cells","chapter":"The idea","kind":"info","eyebrow":"See the shape","title":"One island spans many cells","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"shape-intro","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"filled":[[0,0],[0,1],[0,2],[1,0],[2,0],[3,2],[3,3]],"changed":[]}}]},"body":["The top-left island covers five cells that wind down a column. The bottom-right island covers two.","A plain sweep across the grid lands on each cell in turn, but a single island holds many cells, so the sweep meets the same island more than once and never sees its size in one place.","To know an area, the cells of one island have to be gathered together before the answer is read."]},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which way of measuring should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"r":0,"c":0,"best":0}}]}},{"id":"report-size","chapter":"The idea","kind":"case-probe","eyebrow":"Find the move","title":"You stand on one land cell. How does the search report the size of its island?","summary":"The search has just reached the top-left land cell.","workspacePanel":"visualizer","options":[{"id":"one-plus-neighbors","label":"Count this cell as 1, then add the sizes its four neighbors report back","rationale":"Each cell contributes 1 and asks its neighbors for theirs, so the totals add up the whole connected region one cell at a time.","isCorrect":true},{"id":"just-one","label":"Report 1, since the search is standing on a single cell","rationale":"That measures only the starting cell. The neighbors are still land and their cells go uncounted.","isCorrect":false},{"id":"count-launches","label":"Report how many separate searches were started","rationale":"That counts islands, not their size. The answer here is an area, the number of cells in one region.","isCorrect":false}],"answer":"Count this cell as 1 and add what its four neighbors report. Each land cell adds its own 1 and passes the question on, so the returned number is the size of the whole region.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"report-size-state","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"r":0,"c":0}}]}},{"id":"keep-the-max","chapter":"The idea","kind":"case-probe","eyebrow":"Find the answer","title":"Two searches finish with areas 5 and 2. What is the answer for the grid?","summary":"The scan measures every island in turn, and the grid wants one number out.","workspacePanel":"visualizer","options":[{"id":"max","label":"5, the larger of the two areas","rationale":"The answer is the biggest island, so each completed area is folded into the best with a maximum and 5 wins.","isCorrect":true},{"id":"sum","label":"7, the two areas added together","rationale":"Adding areas measures total land across the grid. With islands of 5 and 2, the largest island area is 5.","isCorrect":false},{"id":"last","label":"2, the area of the island measured last","rationale":"Keeping only the latest area throws away the larger 5 that was already found. Order of scanning must not decide the answer.","isCorrect":false}],"answer":"5. Each island area is folded into the best with a maximum, so the larger 5 survives and the smaller 2 leaves it unchanged.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"keep-the-max-state","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"filled":[[0,0],[0,1],[0,2],[1,0],[2,0],[3,2],[3,3]],"changed":[]}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Sweep, measure each island, keep the largest","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"r":2,"c":0,"filled":[[0,0],[0,1],[0,2],[1,0]],"changed":[],"best":0}}]},"body":["The best area starts at 0. The sweep moves across the grid row by row.","On water it keeps going. On fresh land it runs one search that sinks the whole island, counting the cells it consumes, then folds that size into the best with a maximum.","Because each island is sunk the first time it is reached, the sweep measures every island exactly once."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the sweep","title":"Sink each island and measure it on the way","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-island","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2],[1,0],[2,0]],"changed":[],"best":0}},{"id":"fold-first","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"filled":[[0,0],[0,1],[0,2],[1,0],[2,0]],"changed":[],"best":5}},{"id":"second-island","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"r":3,"c":2,"filled":[[0,0],[0,1],[0,2],[1,0],[2,0],[3,2],[3,3]],"changed":[[3,2],[3,3]],"area":2,"best":5}}]},"beats":[{"id":"first-island","title":"The search sinks the top-left island. What area does it report?","summary":"The best area is 0 and the search starts on fresh land at the corner.","prompt":"The search runs from the top-left land cell through every cell connected to it.","options":[{"id":"five","label":"5","rationale":"Five cells wind down from the corner, each adding its own 1, so the search returns 5.","isCorrect":true},{"id":"one","label":"1, only the cell it started on","rationale":"The neighbors are land too. The search adds each connected cell, so it reports 5, not 1.","isCorrect":false},{"id":"three","label":"3, only the cells in the top row","rationale":"The island bends down a column past the top row, so those cells count as well, giving 5.","isCorrect":false}],"answer":"The search consumes all five connected cells and returns an area of 5."},{"id":"fold-first","title":"The first area of 5 comes back. What is the best area now?","summary":"The best area was 0 before this island was measured.","prompt":"The search returned 5 and the best area still reads 0.","options":[{"id":"becomes-5","label":"5","rationale":"The maximum of 0 and 5 is 5, so the best area rises to 5.","isCorrect":true},{"id":"stays-0","label":"Still 0, until the scan finishes","rationale":"The best area is folded in as each island finishes, not held back to the end, so it becomes 5 now.","isCorrect":false},{"id":"adds-to-5","label":"5 added to 0 on every later island","rationale":"The fold keeps the larger area seen so far. It does not accumulate separate islands together.","isCorrect":false}],"answer":"The best area becomes 5, the maximum of the previous 0 and this island area of 5."},{"id":"second-island","title":"A second island of area 2 finishes. What does the best area become?","summary":"The bottom-right pair is a separate region; the best area already holds 5.","prompt":"The later search returns an area of 2 while the best area reads 5.","options":[{"id":"still-5","label":"5","rationale":"The maximum of 5 and 2 is 5, so the smaller, later island leaves the best area unchanged.","isCorrect":true},{"id":"now-2","label":"2, the area just measured","rationale":"Taking the latest area would discard the larger 5 already found. The fold keeps the larger value.","isCorrect":false},{"id":"now-7","label":"7, the two areas added","rationale":"Adding areas measures total land. The answer is the largest single island, which is 5.","isCorrect":false}],"answer":"5. The maximum of 5 and 2 is 5, so the sweep ends with the best area at 5."}]},{"id":"overwrite-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Do we really need to sink the cell before exploring?","summary":"Leaving the cell as land and recursing straight into the four neighbors counts the same cells, and the bookkeeping looks lighter. Watch it on a two-cell island.","workspacePanel":"trace","pitfall":"The search below adds 1 for the cell and recurses into its neighbors without first setting the cell to 0, so nothing records that the cell was already counted.","whyItMatters":"Sinking the cell as it is counted is what makes each cell contribute exactly once and lets the search end. Without it the search steps right, then back left into a cell it already counted, and loops between the two cells forever.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    cols = len(grid[0])\n    def dfs(r: int, c: int) -> int:\n        if c < 0 or c >= cols or grid[r][c] == 0:\n            return 0\n        area = 1\n        area += dfs(r, c + 1)\n        area += dfs(r, c - 1)\n        return area\n    return dfs(0, 0)","steps":[{"id":"count-left","title":"The left cell counts itself as 1","codeLine":6,"summary":"grid = [[1, 1]]. The search starts on the left land cell at (0,0) and counts it as 1, but never sets grid[0][0] to 0.","state":{"grid":[[1,1]],"r":0,"c":0,"filled":[[0,0]],"changed":[[0,0]],"area":1}},{"id":"step-right","title":"It recurses right onto the second cell","codeLine":7,"summary":"From (0,0) the search steps right to (0,1), which is still land, and counts it as 1 as well, lifting the running area to 2.","state":{"grid":[[1,1]],"r":0,"c":1,"filled":[[0,0],[0,1]],"changed":[[0,1]],"area":2}},{"id":"step-back-left","title":"From the right cell it steps back left","codeLine":8,"summary":"The right cell at (0,1) now recurses left to (0,0). That cell was counted already, but it still reads as land, so the search enters it again and the area climbs to 3.","state":{"grid":[[1,1]],"r":0,"c":0,"filled":[[0,0],[0,1]],"changed":[],"area":3}},{"id":"recount-forever","title":"The two cells recount each other with no end","codeLine":7,"summary":"At (0,0) the search steps right to (0,1) again, which steps left to (0,0) again. Neither cell was ever sunk, so the area runs past 4 and keeps climbing while the search never stops.","state":{"grid":[[1,1]],"r":0,"c":1,"filled":[[0,0],[0,1]],"changed":[],"area":4}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const cols = grid[0].length;\nfunction dfs(r, c) {\n    if (c < 0 || c >= cols || grid[r][c] === 0) {\n        return 0;\n    }\n    let area = 1;\n    area += dfs(r, (c + 1));\n    area += dfs(r, (c - 1));\n    return area;\n}\nreturn dfs(0, 0);","lineMap":{"2":1,"4":3,"5":4,"6":6,"7":7,"8":8,"9":9,"10":11},"statementBundles":{"2":{"startLine":1,"endLine":2},"5":{"startLine":4,"endLine":5},"9":{"startLine":9,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const cols = grid[0].length;\nfunction dfs(r: number, c: number): number {\n    if (c < 0 || c >= cols || grid[r][c] === 0) {\n        return 0;\n    }\n    let area = 1;\n    area += dfs(r, (c + 1));\n    area += dfs(r, (c - 1));\n    return area;\n}\nreturn dfs(0, 0);","lineMap":{"2":1,"4":3,"5":4,"6":6,"7":7,"8":8,"9":9,"10":11},"statementBundles":{"2":{"startLine":1,"endLine":2},"5":{"startLine":4,"endLine":5},"9":{"startLine":9,"endLine":10}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int cols = grid[0].Count;\nint Dfs(int r, int c) {\n    if (c < 0 || c >= cols || grid[r][c] == 0) {\n        return 0;\n    }\n    int area = 1;\n    area += Dfs(r, c + 1);\n    area += Dfs(r, c - 1);\n    return area;\n    return 0;\n}\nreturn Dfs(0, 0);","lineMap":{"2":1,"4":3,"5":4,"6":6,"7":7,"8":8,"9":9,"10":12},"statementBundles":{"2":{"startLine":1,"endLine":2},"5":{"startLine":4,"endLine":5},"9":{"startLine":9,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int, int)> dfs;\n\nint cols = grid[0].size();\ndfs = [&]( int r, int c ) -> int {\n    if (((c < 0 || c >= cols) || grid[r][c] == 0)) {\n        return 0;\n    }\n    int area = 1;\n    area += dfs(r, (c + 1));\n    area += dfs(r, (c - 1));\n    return area;\n};\nreturn dfs(0, 0);","lineMap":{"2":3,"4":5,"5":6,"6":8,"7":9,"8":10,"9":11,"10":13},"statementBundles":{"2":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"9":{"startLine":11,"endLine":12}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int dfs(int r, int c, int cols, List<List<Integer>> grid) {\n    if (((c < 0 || c >= cols) || grid.get(r).get(c) == 0)) {\n        return 0;\n    }\n    int area = 1;\n    area += dfs(r, (c + 1), cols, grid);\n    area += dfs(r, (c - 1), cols, grid);\n    return area;\n}\n\nint cols = grid.get(0).size();\nreturn dfs(0, 0, cols, grid);","lineMap":{"2":11,"4":2,"5":3,"6":5,"7":6,"8":7,"9":8,"10":12},"statementBundles":{"5":{"startLine":3,"endLine":4},"9":{"startLine":8,"endLine":9}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Sweeping the grid, sinking each island, and keeping the largest area handled the sample cleanly, and the maximum held onto the 5-cell island even after a smaller one finished.","Two thin grids are worth a look before you code: a grid that is a single land cell, and land cells that touch only at the diagonal."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"r":0,"c":0,"best":0}}]}},{"id":"single-land-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What area does a grid with one land cell return?","summary":"The single land cell has water or the grid edge on all four sides.","workspacePanel":"visualizer","options":[{"id":"one","label":"1","rationale":"The cell counts as 1, and all four neighbor searches step off the grid and return 0, so the area is 1.","isCorrect":true},{"id":"zero","label":"0","rationale":"Land must count. The cell itself adds 1 before the boundary checks return 0 for its neighbors.","isCorrect":false},{"id":"four","label":"4, one for each direction searched","rationale":"The four neighbors are all off the grid and contribute 0. Only the cell itself counts, giving 1.","isCorrect":false}],"answer":"1. The cell counts as 1, then each of its four neighbors falls off the grid and returns 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-land-state","state":{"grid":[[1]],"filled":[[0,0]],"changed":[]}}]}},{"id":"diagonal-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What is the largest area when land only touches diagonally?","summary":"Land sits at the top-left and bottom-right corners, touching only at the diagonal.","workspacePanel":"visualizer","options":[{"id":"one","label":"1","rationale":"Only four directions connect, so the diagonal does not join the cells. Each is its own island of area 1, and the largest is 1.","isCorrect":true},{"id":"two","label":"2, since the cells touch at the corner","rationale":"A diagonal touch is not a four-direction link, so the two cells are separate islands of area 1 each.","isCorrect":false},{"id":"zero","label":"0","rationale":"There is land, so the largest area is at least 1, not 0.","isCorrect":false}],"answer":"1. The diagonal does not connect the cells, so each is its own island of area 1 and the largest area is 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"diagonal-state","state":{"grid":[[1,0],[0,1]],"filled":[[0,0],[1,1]],"changed":[]}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Each search returns its island size, and a maximum keeps the largest across the scan.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[1,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,1,1]],"r":0,"c":0,"best":0}}]},"body":["Walk every cell. The first time you step onto fresh land, run one search that sinks the whole island and reports how many cells it covered, then keep the larger of that area and the best so far. The part to get right is the fold: a maximum, never an assignment, so a smaller later island cannot overwrite a larger one."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the area count","eyebrow":"Code the rule","summary":"Now turn the rule into code: start the best area at zero, scan every cell, and on fresh land run a search that stops at water and the edge, sums its four neighbors, and folds the returned size into the best with a maximum, then return that best.","workspacePanel":"code","checkpoints":[{"id":"init-best-area","title":"Start the best area at zero","description":"Hold the largest island area found so far in one numeric state.","commonMistakes":["Starting from 1 even when the grid might hold no land","Seeding the answer with the grid dimensions"],"hint":"Before any land is found, the largest area known is zero.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count"}]},"semanticSpec":{"intent":"Initialize the best-area numeric state before scanning the grid.","doneWhen":"A numeric answer state starts at 0 before any island is measured.","roles":["best area","answer state"],"mustProve":["A numeric state for the answer is initialized to zero."],"mustNotAccept":["A nonzero initial answer."],"equivalentVariants":["Any named accumulator seeded to zero before the scan begins."],"proofSnippets":[{"id":"py-max-area-init-best","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0"}]}},{"id":"scan-grid","title":"Visit every cell of the grid","description":"Walk every row and column so no island start is missed.","commonMistakes":["Stopping before the last row or column","Walking only one dimension"],"hint":"Any cell could be the first fresh land of a new island.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops"}]},"semanticSpec":{"intent":"Visit every grid coordinate as a candidate island start.","doneWhen":"A two-level traversal covers every cell of the matrix.","roles":["row index","column index","grid cell"],"mustProve":["The traversal reaches each row and each column."],"mustNotAccept":["A scan that cannot reach every cell."],"equivalentVariants":["Any full-matrix scan that exposes every cell to the land check."],"proofSnippets":[{"id":"py-max-area-scan-grid","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    for r in range(len(grid)):\n        for c in range(len(grid[0])):\n            cell = grid[r][c]"}]}},{"id":"check-land","title":"Measure only from fresh land","description":"Begin a search only when the current cell is land that has not been sunk yet.","commonMistakes":["Searching from water","Re-entering land a previous search already sank"],"hint":"The search should begin only when the cell is land.","validation":{"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"}]},"semanticSpec":{"intent":"Gate the island measurement on a fresh land cell.","doneWhen":"The search entry runs only for a cell whose value is land.","roles":["fresh land","component entry"],"mustProve":["The current cell is compared with the land value before the search begins."],"mustNotAccept":["An unconditional search from every cell."],"equivalentVariants":["Any branch that treats only unsunk land as a new island start."],"proofSnippets":[{"id":"py-max-area-check-land","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    for r in range(len(grid)):\n        for c in range(len(grid[0])):\n            if grid[r][c] == 1:\n                best = max(best, 1)"}]}},{"id":"dfs-base-case","title":"Stop the search at water and the edge","description":"Return 0 when the search steps off the grid or onto water.","commonMistakes":["Reading the cell before checking the bounds","Returning area for a water cell"],"hint":"A step off the grid or onto water adds no area.","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"}]},"semanticSpec":{"intent":"Keep the search inside the grid and only on land.","doneWhen":"The search returns 0 before any change when the cell is out of bounds or water.","roles":["boundary guard","water guard","zero area"],"mustProve":["Bounds and water checks guard the recursion."],"mustNotAccept":["Recursing through water or off the grid."],"equivalentVariants":["Any guard that returns zero area before stepping into an invalid cell."],"proofSnippets":[{"id":"py-max-area-dfs-base-case","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    rows, cols = len(grid), 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        return 1\n\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                best = max(best, 1)"}]}},{"id":"explore-neighbors","title":"Sum the four neighbor areas","description":"Sink the current cell, then add the areas the four cardinal neighbors report back.","commonMistakes":["Leaving out one direction","Stepping to diagonal cells"],"hint":"A region is one for this cell plus the areas its four neighbors return.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"explores_grid_neighbors","scope":"explore-neighbors","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Accumulate all four-directionally connected land into the region area.","doneWhen":"The search adds the areas from the up, down, left, and right neighbors.","roles":["current cell","cardinal neighbors","recursive area"],"mustProve":["Recursive calls move to neighboring grid coordinates.","The helper returns the area accumulator that received those neighbor areas."],"mustNotAccept":["Only one direction, or diagonal movement.","Returning a constant or coordinate instead of the accumulated area."],"equivalentVariants":["Any sum of the four cardinal neighbor searches."],"proofSnippets":[{"id":"py-max-area-explore-neighbors","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    rows, cols = len(grid), 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        area = 1\n        area += dfs(r + 1, c)\n        area += dfs(r - 1, c)\n        area += dfs(r, c + 1)\n        area += dfs(r, c - 1)\n        return area\n\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                best = max(best, 1)"}]}},{"id":"update-best-area","title":"Keep the larger of best and this area","description":"Run the search from the fresh land cell and fold its returned area into the best area with a maximum.","commonMistakes":["Overwriting the best area with the latest island area","Adding the island areas together instead of taking the largest"],"hint":"After a search finishes, the best area is the larger of itself and the area just returned.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_recursive_cell_exploration","scope":"call-dfs","readMode":"grid-recursive-search-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best"}]}]},"semanticSpec":{"intent":"Measure one island and keep the larger of the previous best and this area.","doneWhen":"The search result is compared against the best area and the best state keeps the larger value.","roles":["current area","best area","maximum update"],"mustProve":["The returned island area flows into a maximum update of the best state."],"mustNotAccept":["Overwriting the best area with the last island, or summing the islands."],"equivalentVariants":["Any maximum that folds the returned area into the best state."],"proofSnippets":[{"id":"py-max-area-update-best","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    rows, cols = len(grid), 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        area = 1\n        area += dfs(r + 1, c)\n        area += dfs(r - 1, c)\n        area += dfs(r, c + 1)\n        area += dfs(r, c - 1)\n        return area\n\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                best = max(best, dfs(r, c))"}]}},{"id":"return-best-area","title":"Return the best area","description":"After the whole grid is scanned, return the largest area state.","commonMistakes":["Returning the grid","Returning the last island area instead of the largest"],"hint":"Return the best-area state after the scan finishes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_extremum_numeric_state","scope":"return-profit"}]},"semanticSpec":{"intent":"Return the maximum-area state after every island is measured.","doneWhen":"The final return is the same numeric state updated by the maximum.","roles":["best area","answer"],"mustProve":["The returned numeric state is the tracked maximum."],"mustNotAccept":["Returning grid dimensions or the sunk grid."],"equivalentVariants":["Return the same accumulator the maximum updates."],"proofSnippets":[{"id":"py-max-area-return-best","language":"python","code":"def maxAreaOfIsland(grid: list[list[int]]) -> int:\n    best = 0\n    rows, cols = len(grid), 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        area = 1\n        area += dfs(r + 1, c)\n        area += dfs(r - 1, c)\n        area += dfs(r, c + 1)\n        area += dfs(r, c - 1)\n        return area\n\n    for r in range(rows):\n        for c in range(cols):\n            if grid[r][c] == 1:\n                best = max(best, dfs(r, c))\n    return best"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Each search returns its island size, and a maximum keeps the largest across the whole grid.","workspacePanel":"code","body":["Scan for fresh land; one search sinks the island and returns its area, counting each cell once.","Fold every returned area into the best with a maximum, so the largest island survives no matter when it is found."],"takeaways":[{"title":"The search returns an island size","body":"Each land cell adds 1 and sums its four neighbors, so one dive measures the whole connected region."},{"title":"Keep the largest island area","body":"Folding each area in with a maximum keeps the largest island even when a smaller one is found later."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
