Number of Islands

Medium Graphs

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'

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

Watch the explanation

More Graphs

All Graphs problems