Maintained by Vikas Dulgunde, software engineer
You receive a rectangular grid where every cell holds either 1 for land or 0 for water. An island is any group of land cells joined to each other through shared edges, so two cells belong to the same island when one sits directly above, below, left, or right of the other. Diagonal contact does not link cells.
The area of an island is simply how many land cells it contains. Your job is to scan the whole grid, identify every separate island, and report the largest area among them.
If the grid holds no land at all, there is no island to measure, so the answer is 0. Otherwise the answer is at least 1, since a lone land cell with water on every side is still an island of area 1.
Every cell except the center is land, and all eight land cells touch through shared edges around the ring, forming one island of size 8. The single water cell in the middle does not split the ring.
There are two islands. The two stacked land cells on the left form an island of size 2. The cluster on the right (two stacked cells plus one to the right of the lower one) has size 3, so the answer is 3.
The grid is all water, so no island exists and the maximum area is 0.
Visible test cases
When you land on an unvisited 1, you have found the corner of some island. How would you measure the whole island starting from that one cell?
Treat the grid like a graph: each land cell is a node, and edges run to the four orthogonal neighbors that are also land. Flood out from the starting cell, counting cells as you go.
To avoid counting the same cell twice, mark each visited land cell (for example, overwrite it to 0) the moment you reach it. Track the best area seen across all starting cells.
Walk every cell once. The first time you touch a land cell that has not been counted, run a flood fill that visits the entire island it belongs to, returns its size, and marks each visited cell so it is never recounted. The answer is the largest size any flood fill returns.
Same flood-fill idea, but use an explicit queue instead of recursion. This sidesteps deep call stacks if you prefer iteration, while keeping the linear time bound.