AlgoLounge

Number of Islands

medium

Given an m x n 2D binary grid grid which represents a map of 1s (land) and 0s (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

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 There is 1 island (all the 1s are connected).

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 There are 3 separate islands.

Example 3

Input:  grid = [

[1,0,1,0,1], [0,1,0,1,0], [1,0,1,0,1], [0,1,0,1,0] ] Output: 10 Each 1 is its own island (no adjacent lands).

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is 0 or 1
TypeScript
Loading editor…
List of test cases (10)
Case 1
grid = [[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]]
Case 2
grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]
Case 3
grid = [[1,0,1,0,1],[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0]]
Case 4
grid = [[1,1,1],[0,1,0],[1,1,1]]
Case 5
grid = [[0,0,0],[0,0,0],[0,0,0]]
Case 6
grid = [[1]]
Case 7
grid = [[0]]
Case 8
grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Case 9
grid = [[1,0,1,1,0,1]]
Case 10
grid = [[1,0,0],[0,1,0],[0,0,1]]