Number of Islands

medium

Given an R × C grid of 1s (land) and 0s (water), return the number of islands. An island is a maximal group of 1s connected 4-directionally (up, down, left, right). The grid's borders are surrounded by water.

Hints

Treat the grid as a graph: each land cell connects to its 4 orthogonal land neighbours.
Scan for an unvisited land cell — that's a new island — then flood it.
Sink flooded land to 0 to mark it without a separate visited array.

Common doubts

Both are O(R·C) and give the same count. BFS (iterative) avoids stack overflow when a single island fills a large grid.
Once a land cell is counted as part of an island, it never needs to be revisited, so overwriting it with water is fine.
Yes — union adjacent land cells and count the land components; useful when cells are added incrementally (islands II).

Interview follow-ups

Add the 4 diagonal directions to the neighbour set — 8-directional flood.
Union-Find (Islands II): union each new land cell with adjacent land and track the running count.

Fun facts

  • LeetCode 200 — the canonical grid-flood problem behind dozens of variants.
  • The 'sink the island' trick is the grid analogue of a visited array.

Asked at

AmazonMicrosoftGoogleFacebook
Frequently Sometimes Occasionally
Example 1
Input: grid = [[1,1,0],[0,1,0],[0,0,1]]
Output: 2
One L-shaped island and one single-cell island.
Example 2
Input: grid = [[0,0],[0,0]]
Output: 0
All water.
Constraints

- 1 <= R, C <= 300 - grid[i][j] is 0 or 1

Solve this problem →