Island Count
Given a 2D grid map of 1s (land) and 0s (water), count 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 surrounded by water.
[ [ 1, 1, 1, 0, 0 ], [ 1, 1, 0, 0, 0 ], [ 1, 0, 0, 1, 1 ], [ 0, 0, 0, 0, 1 ] ]
Explanation. There are three islands. One consists of the first three `1`s in the first row and the first two `1`s in the second row, another consists of the last two `1`s in the third row, and the third consists of the last `1` in the last row.
[ [ 1, 0, 1 ], [ 0, 1, 0 ], [ 1, 0, 1 ] ]
Explanation. Each land cell that is separated by water forms an island. There are a total of five islands in this grid.
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
Explanation. As there is no land (`1`), there are no islands in this grid.
Follow-up: What modifications would be needed if we also consider diagonal connections?
The grid will be a non-empty 2D array.
- Views
- 2