Number of Islands

Medium Graphs AI round

grid is a map of m rows and n columns. Each cell holds the character '1' for land or '0' for water.

Land cells that share a side, one above, below, left or right of the other, belong to the same island. Cells that meet only at a corner do not, and everything beyond the edge of the map is water.

Return the number of islands in grid.

Example 1

Input: grid = [["1","1","0","0","1","1"],["1","0","0","0","0","1"],["0","0","0","1","0","0"],["0","1","1","1","0","0"],["0","0","0","0","0","1"]]
Output: 4

Four islands: three land cells in the top left corner, three in the top right corner, four in the middle that join by their sides, and one cell alone at the bottom right.

Example 2

Input: grid = [["1","0","1"],["0","1","0"],["1","0","1"]]
Output: 5

Example 3

Input: grid = [["1","1","1"],["1","0","1"],["1","1","1"]]
Output: 1

Constraints

  • 1 ≤ m, n ≤ 1000
  • m · n ≤ 10⁵
  • Every row of grid has n cells
  • grid[i][j] is '0' or '1'

Watch the explanation

More Graphs

All Graphs problems