Count Islands in a Binary Board
Problem statement
Return the number of islands in grid.
For this exercise, assume grid is a rectangular board represented by equal-width strings of 0 and 1. A 1 is land and a 0 is water. An island is a maximal group of land cells connected by steps up, down, left or right. Diagonal contact does not connect cells, and an island may have any shape.
For this exercise, assume you count all islands across the board and return one integer. Do not modify the input. An empty board or a board containing only water returns 0.
Function
countIslands(grid: String[]) → intExamples
Example 1
grid = ["11000","11000","00100","00011"]return = 3The two-by-two upper-left block, the center cell and the lower-right pair are three components. Diagonal contact does not connect them.
Example 2
grid = ["111","101","111"]return = 1The land ring is one component even though it is not a filled rectangle.
Example 3
grid = []return = 0An empty board has no components.
Constraints
- For this exercise, assume
0 <= grid.length <= 30. - For a nonempty board, every row has the same length from
1through30. - Every row contains only
0and1.