Skip to content
Problem 695 · LeetCode 695(opens in a new tab)

Max Area of Island

MediumDepth-first search

You are given a grid of 0s and 1s, grid, with m rows and n columns. A 1 is land and a 0 is water. Land cells that touch on a side (up, down, left or right) belong to the same island; touching only at a corner does not count. Everything outside the grid is water.

The area of an island is how many land cells it has. Return the area of the biggest island, or 0 when the grid has no land.

Example 1

Input:  grid = [[1,0,0,0],
                [1,0,0,0],
                [1,0,1,0],
                [0,1,1,1]]
Output: 4
Why:    the lower right island has 4 cells, the left one 3
2 more examples and the constraints

Example 2

Input:  grid = [[1,1,0],
                [0,0,1],
                [0,1,1]]
Output: 3
Why:    the corner touch does not join the two islands

Example 3

Input:  grid = [[0,0],
                [0,0]]
Output: 0
Why:    no land at all

Constraints

  • 1 ≤ m, n ≤ 50
  • Every cell is 0 or 1

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Flood fill from every land cellO((m·n)²)
  2. Visit each island onceO(m·n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 50 × 50 grid of landVerdict
Flood fill from every land cellO((m·n)²)
Mention it, then move on
Visit each island onceO(m·n)
Best; each cell once

m = rows, n = columns.

Edge cases to test

  • No land. Return 0, not a negative number or an error.
  • Corners only. Cells that touch diagonally are separate islands.
  • All land. One island covering the whole grid: the area is m·n.
  • One row or one column. Bounds checks must hold when the grid is a single line.

Common mistakes

  • Marking a cell visited when it is popped instead of when it is pushed, so the same cell is counted twice.
  • Counting diagonal neighbours as connected.
  • Recursing on a large island and hitting the recursion limit in Python.

How to talk through it

  1. 1Clarify. Do diagonals connect? May I change the grid in place? What do I return with no land?
  2. 2Give the brute force. Flood from every land cell with a fresh visited set; say each island is measured once per cell.
  3. 3Visit once. Mark land as visited when it is pushed, so each island is flooded exactly once.
  4. 4Code the fill. A scan, a stack, area += 1 per pop, and four neighbours with a bounds check.
  5. 5Test out loud. Run an all-water grid, a diagonal-only grid, and a single row.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?