Number of Islands
Given a 2D grid of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent land cells horizontally/vertically.
Input: grid, a 2D list whose cells are the single-character strings '1' and '0' (the example shows each row as comma-separated values). Return the island count as an integer.
Example
1,1,1,1,0 1,1,0,1,0 1,1,0,0,0 0,0,0,0,0
1
gridhas rows and columns; each cell is the character1(land) or0(water). Writing cell positions as (row, column) from , the land cells are: all of row 0 except column 4, then , then — land cells in total. Row 3 is all water.- Two land cells belong to the same island when you can walk from one to the other through land, stepping only up, down, left or right.
- The left block – is a solid patch of land, joined to and along row 0. The cell sits directly below , so it is joined too, even though water at separates it from .
- Every one of the land cells is reachable from every other, so there is exactly one island and the answer is
1. - Notice that diagonal contact does not count: a lone
1touching another only at a corner is its own island. A grid with no1at all gives .
Constraints
- 1 <= rows, cols <= 300
- grid[i][j] is '0' or '1'