Max Area of Island (LeetCode 695): Solution and Explanation

Medium
Array
Depth First Search
Breadth First Search
Union Find
Matrix

A grid of 0s and 1s marks water and land. Land cells that touch up, down, left or right belong to the same island. Return the number of cells in the largest island, or 0 if there is no land at all.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

This is the counting version of the classic island problem. Instead of asking how many islands exist, it asks how big the biggest one is, but the structure of the solution is the same: treat the grid as a graph where each land cell connects to its land neighbors, and find connected components.

A naive approach might try to compute, for every land cell, the size of the island it belongs to. That repeats the same flood fill many times over, once per cell in each island, and on a grid that is all land it becomes quadratic in the number of cells.

The fix is to explore each island exactly once. Scan the grid, and whenever you hit a land cell that has not been explored, launch a depth-first search from it. The DFS returns how many cells it reached: each call counts its own cell as 1 and adds whatever its four neighbors return. Out-of-bounds positions and water return 0, which keeps the recursion simple.

To guarantee that no cell is counted twice, the DFS sinks every cell it visits by setting it to 0 before exploring the neighbors. That doubles as the visited set, so no extra memory is needed, and it means later scan positions inside the same island are skipped automatically. The answer is the largest area any DFS returns.

Approach: DFS flood fill with in-place marking

  1. Return 0 for an empty grid, and record rows, cols and max_area = 0.
  2. Define dfs(r, c) that returns 0 if the position is out of bounds or grid[r][c] == 0.
  3. Otherwise set grid[r][c] = 0 to mark it visited, and start area at 1 for this cell.
  4. Add the results of dfs on the four neighbors (down, up, right, left) to area and return it.
  5. Scan every cell, and when grid[r][c] == 1, update max_area with the area returned by dfs(r, c).
  6. Return max_area after the scan.

Step-by-step example

grid = [[1,1,0,0],[1,0,0,1],[0,0,1,1],[0,0,0,1]]
  1. The scan reaches (0,0), which is land, so a DFS begins there and sinks it.
  2. From (0,0) the DFS goes down to (1,0), which is land and has no further land neighbors, so it returns 1. Going right reaches (0,1), which also returns 1. The DFS at (0,0) returns 1 + 1 + 1 = 3, and max_area becomes 3.
  3. The scan passes (0,1) and (1,0), which are now 0, and reaches (1,3), the next land cell.
  4. From (1,3) the DFS goes down to (2,3). From there it goes down to (3,3), worth 1, and left to (2,2), worth 1. So (2,3) returns 3 and (1,3) returns 4.
  5. max_area becomes 4. Every remaining cell is water, so the answer is 4.

Code: Python, Java, C++

1class Solution:
2    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
3        if not grid:
4            return 0
5
6        rows, cols = len(grid), len(grid[0])
7        max_area = 0
8
9        def dfs(r, c):
10            if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0:
11                return 0
12            grid[r][c] = 0  # Mark as visited
13            area = 1
14            area += dfs(r + 1, c)
15            area += dfs(r - 1, c)
16            area += dfs(r, c + 1)
17            area += dfs(r, c - 1)
18            return area
19
20        for r in range(rows):
21            for c in range(cols):
22                if grid[r][c] == 1:
23                    max_area = max(max_area, dfs(r, c))
24
25        return max_area

Time and space complexity

Time

O(m × n)

The scan touches every cell once, and each land cell is sunk and expanded by exactly one DFS call. Each call does constant work besides its four neighbor checks, so the total is proportional to the number of cells.

Space

O(m × n)

Marking happens in place, but the recursion can go as deep as the size of the largest island, which is all m × n cells for a grid full of land.

Other approaches

BFS with a queue (time O(m × n), space O(min(m, n)))

Replace the recursion with a queue: push the starting cell, mark it, and count cells as you pop them while pushing unvisited land neighbors. It avoids recursion depth limits in Python on large grids, and its queue only holds the frontier.

Union-find (time O(m × n × α(m × n)), space O(m × n))

Union each land cell with its land neighbors and track the size of each set. The largest set size is the answer. It is overkill here but useful when land cells arrive over time.

Common mistakes

  • Marking the cell visited after exploring the neighbors instead of before. Two neighbors then recurse into each other forever, or cells get counted twice.
  • Counting islands rather than measuring them, for example adding 1 per DFS launch instead of using the returned area.
  • Hitting Python's recursion limit on large all-land grids. Raise the limit or switch to an iterative stack or BFS when the grid can be big.
  • Including diagonal neighbors. Only the four orthogonal directions connect land in this problem.

Frequently asked questions

What is the time complexity of Max Area of Island?

O(m × n). Every cell is looked at by the outer scan, and every land cell is visited by exactly one DFS, because it is set to 0 the first time it is reached.

Can I avoid modifying the input grid?

Yes. Use a separate visited set or boolean matrix instead of overwriting cells with 0. It costs O(m × n) extra memory but leaves the input intact.

BFS or DFS for Max Area of Island?

Both have the same time complexity. DFS is the shortest to write, while BFS or an explicit stack avoids deep recursion, which matters in Python on large grids.