Practice · Graphs · 1 of 3

Count the Islands

You are given grid, a map made of 1s (land) and 0s (water). An island is a group of land cells joined up, down, left or right; cells that only touch diagonally are not joined. Everything outside the grid is water.

Return the number of islands.

Example 1

Input
grid = [[1, 1, 0, 0, 1], [0, 1, 0, 1, 1], [1, 0, 0, 0, 0], [1, 0, 1, 1, 0]]
Output
4
The islands are at the top left, the top right, the bottom left and the bottom middle. The cells at (1, 1) and (2, 0) only touch diagonally, so they are on different islands.

Example 2

Input
grid = [[0, 0], [0, 0]]
Output
0
No land, so no islands.

Constraints

  • The grid has 1 to 200 rows and 1 to 200 columns.
  • Every cell is 0 or 1.