Count Connected Islands
Problem statement
You are given a rectangular binary matrix grid. A cell containing 1 is land and a cell containing 0 is water. Land cells belong to the same island when they are connected horizontally or vertically.
Return the number of islands.
Function
numberOfIslands(grid: int[][]) → intExamples
Example 1
grid = [[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]]return = 1All land cells are connected through horizontal or vertical moves.
Example 2
grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]return = 3The top-left block, center cell, and bottom-right pair are separate islands.
Example 3
grid = [[0,0],[0,0]]return = 0No cell is land.
Constraints
1 <= grid.length <= 300.1 <= grid[i].length <= 300.- Every row has the same length.
- Every value is
0or1.