AlgoFrames

Number of islands

Standard · Write code · about 12 min

A grid holds 1 for land and 0 for water. An island is a group of land cells joined up, down, left or right. Return the number of islands.

Example 1

Input:

[[[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]]

Output:

3

The 2 × 2 block, the single cell and the 2 × 2 corner block.

Example 2

Input:

[[[1,0],[0,1]]]

Output:

2

Corner contact does not join cells.

Constraints

  • 1 ≤ rows, cols ≤ 50
  • grid[r][c] is 0 or 1

Learn the idea first: Connected components and flood fill, a visual lesson.

More Connected components and flood fill problems