Given a grid of 0s and 1s, return the area of the largest island — a connected group of 1s, connected horizontally or vertically. Return 0 if there is no island.
Example
Input grid = [[0,1,1,0],[0,1,0,0],[0,0,0,1]]
Output 3
Key Pointers
Same flood-fill scan as Number of Islands, but track the size of each island instead of just counting them.
A DFS naturally accumulates a count as it unwinds — 1 for the current cell plus whatever each valid neighbor contributes.
Keep a running maximum across every island found during the full scan.
Step-by-Step Analysis
Scan every cell in the grid.
When an unvisited 1 is found, run DFS from it, marking cells visited and summing 1 per land cell reached.
Compare that island's total against the running maximum, updating it if larger.
After the full scan, return the maximum area found (0 if there was no land at all).
Complexity
Time: O(rows · cols) — Space: O(rows · cols)
Code
def maxAreaOfIsland(grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0])
visited = set()
def dfs(r: int, c: int) -> int:
if (r < 0 or r >= rows or c < 0 or c >= cols or
grid[r][c] == 0 or (r, c) in visited):
return 0
visited.add((r, c))
return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1)
max_area = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1 and (r, c) not in visited:
max_area = max(max_area, dfs(r, c))
return max_area
Code Explanation
How the solution above works, piece by piece.
dfs(r, c) returns the number of new land cells reachable from (r, c).
It returns 0 for out-of-bounds cells, water, or cells already visited.
Otherwise mark the cell and return 1 + the areas from all 4 neighbours.
The outer loop starts a DFS from every unvisited land cell and keeps the biggest result.
O(rows × cols) time; recursion depth can reach the island size.
Visual Walkthrough
Running it on the example grid:
Each DFS returns how many cells it covered. The top island's DFS counts 3 cells; the single cell in the corner counts 1. The answer is the larger: 3.