Skip to content
Onsite

Number of Islands

MediumP1Coding

You are given a 2D grid grid of characters "1" (land) and "0" (water). Return the number of islands.

An island is a maximal group of land cells connected horizontally or vertically (not diagonally). Cells outside the grid count as water.

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 <= rows, cols <= 300
  • grid[i][j] is "0" or "1"

Hints

Run checks the 3 visible tests, Submit all 11.