Skip to content
CodeShare
All problems

Number of Islands

Count the groups of connected land on a map.

MediumGraphsMatrix

You're given a 2D grid of 1s (land) and 0s (water). An island is a group of land cells connected horizontally or vertically. Return the number of islands.

Everything outside the grid counts as water, and diagonal neighbours are not connected.

Examples

Example 1
Input
grid = [[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0]]
Output
1
Example 2
Input
grid = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1]]
Output
3

Constraints

  • 1 <= grid.length, grid[i].length <= 300
  • grid[i][j] is 0 or 1.