Maintained by Vikas Dulgunde, software engineer
You are handed a rectangular grid where every cell holds either the character '1' for land or '0' for water. A group of land cells that are joined to each other forms a single island. Two land cells count as joined when they sit directly next to each other in a vertical or horizontal direction. Cells that meet only at a corner are not joined.
Your job is to report how many distinct islands the grid contains. Water cells never belong to any island, and the area outside the grid is treated as water, so islands along the edges still count as fully surrounded.
The same land cell can never belong to two islands at once. Once you decide which island a cell is part of, every other land cell reachable from it through up, down, left, or right moves belongs to that same island. The answer is the number of these connected groups.
The three '1's in the top-left corner all touch edge to edge, so they form one island. The lone '1' in the bottom-right corner touches no other land, so it forms a second island. Total: 2.
Each '1' sits in a checkerboard pattern where its only land neighbours are diagonal, which does not count as connected. So all five land cells are isolated and each is its own island.
Every cell is water, so there are no islands.
Visible test cases
Walk the grid cell by cell. The first time you hit a land cell that you have not seen before, you have found a brand-new island, so add one to your count.
After finding that new island, expand outward from it and visit every land cell reachable through up/down/left/right moves, marking each as visited so the outer scan never starts a second island from the same landmass.
Use depth-first or breadth-first search to flood the island. Flipping each visited land cell to '0' in place is a clean way to mark it without a separate visited grid, as long as you are allowed to modify the input.
Scan every cell. Each unvisited '1' starts a new island; from there, traverse all connected land and mark it visited so it is counted only once.
Treat each land cell as a node and union it with its right and down land neighbours. The number of distinct sets among land cells is the island count.