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 32 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 islandsExample 3
Input: grid = [[0,0],
[0,0]]
Output: 0
Why: no land at allConstraints
- 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.
- Flood fill from every land cellO((m·n)²)
- Visit each island onceO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 50 × 50 grid of land | Verdict |
|---|---|---|---|
| Flood fill from every land cell | O((m·n)²) | Mention it, then move on | |
| Visit each island once | O(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
- 1Clarify. Do diagonals connect? May I change the grid in place? What do I return with no land?
- 2Give the brute force. Flood from every land cell with a fresh visited set; say each island is measured once per cell.
- 3Visit once. Mark land as visited when it is pushed, so each island is flooded exactly once.
- 4Code the fill. A scan, a stack, area += 1 per pop, and four neighbours with a bounds check.
- 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?