Skip to content

Max Area of Island

Find the biggest island in a 0/1 grid by letting a DFS return the number of cells it sinks.

MediumGraph BFS and DFS
Solve on LeetCode

The problem

You get a grid grid of 0s and 1s, where 1 is land. An island is a group of land cells joined through up, down, left or right steps, and its area is the number of cells in it. Return the largest area of any island, or 0 if there is no land.

Input grid = [[1, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 1, 0, 0], [1, 1, 1, 0, 0]]

Output 4

The islands have 3, 3 and 4 cells, and the largest is the group of four at the bottom left.

Input grid = [[0, 0], [0, 0]]

Output 0

There is no land, so the largest area is 0.

How to spot the pattern

  • You must measure connected groups in a grid and keep the largest one.
  • A search that visits a whole group can count its cells on the way.

The idea

This is Number of Islands with a size attached. When the scan reaches land, a DFS from there visits the whole island, and if each call returns 1 for its own cell plus whatever its four neighbors return, the first call gives the island's area. Sinking each visited cell (setting it to 0) stops it from being counted twice, by the same island or by the scan.

Brute force: Start a new flood from every land cell, even from cells already counted, which redoes whole islands and costs O((m * n)^2) time.

Step by step

  1. 1Write area(r, c), which returns 0 if the cell is outside the grid or is not land.
  2. 2Otherwise set the cell to 0 and return 1 plus area of its four neighbors.
  3. 3Scan every cell and, at each land cell, compute area(r, c).
  4. 4Keep the largest area seen and return it, which is 0 when the grid has no land.

See the pattern move

The graph bfs and dfs pattern on a small example. Step through it, or press play.

Code

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])

        def area(r: int, c: int) -> int:
            if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != 1:
                return 0
            grid[r][c] = 0  # sink the cell so it is counted only once
            return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1)

        best = 0
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    best = max(best, area(r, c))
        return best

Complexity

Time

O(m * n)

Space

O(m * n)

Each cell is sunk at most once; the recursion stack can hold every cell of one island in the worst case.

Watch out for

  • Visiting the neighbors before sinking the cell, so two neighbors keep counting each other forever.
  • Returning the number of islands instead of the size of the largest one.
  • Returning -1 or 1 when there is no land; the answer is 0.

Follow-up questions

What if you may turn one water cell into land to make the biggest island possible?

Label every island with an id and store its area. Then, for each water cell, add 1 to the areas of the distinct islands around it and keep the best total. That is Making A Large Island.

Can you do it without changing the grid?

Keep a separate visited grid instead of sinking cells; the time stays O(m * n).

In Hinglish

Har land cell se DFS chalao jo apna 1 aur chaaron padosiyon ka area jod ke lautaye. Cell ko 0 karte jao taaki dobara na gina jaaye, aur sabse bada area yaad rakho.

Related problems