← DSA
MEDIUM

Max Area of Island

PracticeNeetCode ↗LeetCode ↗

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

Step-by-Step Analysis

  1. Scan every cell in the grid.
  2. When an unvisited 1 is found, run DFS from it, marking cells visited and summing 1 per land cell reached.
  3. Compare that island's total against the running maximum, updating it if larger.
  4. 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.

  1. dfs(r, c) returns the number of new land cells reachable from (r, c).
  2. It returns 0 for out-of-bounds cells, water, or cells already visited.
  3. Otherwise mark the cell and return 1 + the areas from all 4 neighbours.
  4. The outer loop starts a DFS from every unvisited land cell and keeps the biggest result.
  5. O(rows × cols) time; recursion depth can reach the island size.

Visual Walkthrough

Running it on the example grid:

Two islands of area 3 and 1011001000001island 1: area 3island 2: area 1dfs returns 1 + the areas foundin all 4 directionsmax area = 3
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.
area 3area 1

Video Explanation

NeetCode — LeetCode 695