Problem · Array
Count Connected Islands
Learn this problemProblem statement
You are given a rectangular binary grid encoded as an array of equal-length strings. Character 1 represents land and character 0 represents water.
An island is a maximal group of land cells connected through shared edges. Cells that touch only at a corner are not connected.
Return the number of islands. Do not modify the input grid.
Function
countIslands(grid: String[]) → intExamples
Example 1
grid = ["110","010","101"]return = 3The three connected components are the upper-left group, the land cell at the lower left, and the land cell at the lower right.
Example 2
grid = ["0000","0000"]return = 0Every cell is water, so the grid contains no island.
Constraints
1 <= grid.length <= 5001 <= grid[i].length <= 500- All rows have the same length.
- Every character is
0or1. grid.length * grid[i].length <= 2 * 10^5