You are given an n × n grid of 0s (water) and 1s (land). An island is a group of land cells joined through their up, down, left and right neighbours.
You may turn at most one 0 into a 1. Return the area of the largest island the grid can have after that change.
Example 1
Input: grid = [[1, 1, 0],
[0, 0, 1],
[1, 0, 1]]
Output: 5
Why: turning (0,2) into land joins two islands of 22 more examples and the constraints
Example 2
Input: grid = [[0, 0], [0, 0]] Output: 1 Why: no land at all; the flipped cell is an island of 1
Example 3
Input: grid = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] Output: 9 Why: no 0 to flip; the whole grid is one island
Constraints
- 1 ≤ n ≤ 500
- The grid is square: n rows of n cells
- 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.
- Flip each 0, recountO(n⁴)
- Label islands, then try each 0O(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 500 × 500 grid | Verdict |
|---|---|---|---|
| Flip each 0, recount | O(n⁴) | About 6 × 10¹⁰ steps; too slow | |
| Label islands, then try each 0 | O(n²) | Best; each island measured once |
n = side length of the grid.
Edge cases to test
- All water. No island exists, but flipping any cell makes an island of 1.
- All land. There is no 0 to flip; return n².
- One island on two sides of a 0. In a ring, the centre 0 touches the same island four times; count its area once.
- A 0 between three islands. The flip can merge more than two islands at once; add every distinct neighbour.
- Single cell. [[1]] and [[0]] both give 1.
Common mistakes
- Adding the same island twice when it touches the 0 from two sides.
- Returning 0 for a grid of only water, when one flip gives 1.
- Only trying flips, so a grid with no 0 returns 0 instead of n².
How to talk through it
- 1Clarify. Is the flip optional? Is connection only through the four sides, not diagonals?
- 2Give the brute force. Flip each 0 and recount: O(n⁴), far too slow for 500 × 500.
- 3Find the repeated work. Island areas do not change between tries, so measure each island once and label it.
- 4Combine at each 0. 1 plus the sizes of the distinct labels around it; use a set to avoid double counting.
- 5Test out loud. Run all water, all land and a ring around a single 0.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?