Problem
Same grid-of-land-and-water setup as counting islands, but instead of counting islands, return the area (cell count) of the largest one. Return 0 if there's no land at all.
Signal
The same flood-fill-per-unvisited-land-cell shape as counting islands, but this time the fill needs to hand back how many cells it touched, not just the fact that it ran — a flood fill that returns a size instead of a boolean.
Approach
Scan every cell. On an unvisited land cell, flood fill outward and count how many cells the fill visits, then compare that count against a running maximum. The fill itself is identical to the island-counting version — only what you do with its result changes.
Skeleton
best = 0
for each cell:
if cell is land and not visited:
best = max(best, flood_fill_and_count(cell))
return best
Solution
def max_area_of_island(grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0])
visited = set()
def flood_fill(r: int, c: int) -> int:
stack = [(r, c)]
visited.add((r, c))
area = 0
while stack:
cr, cc = stack.pop()
area += 1
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if (
0 <= nr < rows
and 0 <= nc < cols
and (nr, nc) not in visited
and grid[nr][nc] == 1
):
visited.add((nr, nc))
stack.append((nr, nc))
return area
best = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1 and (r, c) not in visited:
visited.add((r, c))
best = max(best, flood_fill(r, c))
return best
Complexity
O(rows · cols) time — every cell is visited once across all fills combined. O(rows · cols) space for the visited set.
Pitfalls
- Returning the count of fills (like the islands-count problem) instead of the size of the largest fill — an easy mix-up if you've just solved Number of Islands and copy the shape too literally.
- Forgetting the "no land at all" edge case — the loop naturally returns 0
since
beststarts at 0 and the inner condition never triggers, but it's worth stating explicitly if asked. - Off-by-one on grid bounds when checking neighbors — always guard with
0 <= nr < rows and 0 <= nc < colsbefore indexing.