Problem · Matrix
Count Islands with DFS and BFS
Learn this problemProblem statement
You are given a rectangular binary grid in which 1 is land and 0 is water. An island is a maximal group of land cells connected horizontally or vertically.
Return the number of islands. Depth-first search and breadth-first search are alternative required solution strategies for the same result; the function returns one count.
Function
countIslands(grid: int[][]) → intExamples
Example 1
grid = [[1,1,0,0],[1,0,0,1],[0,0,1,1]]return = 2The upper-left land cells form one island, and the connected right-side cells form the other.
Example 2
grid = [[1,0,1],[0,1,0],[1,0,1]]return = 5Diagonal contact does not connect land, so every 1 is a separate island.
Example 3
grid = []return = 0An empty grid contains no land.
Constraints
0 <= rows, columns <= 500.- The grid is rectangular and contains at most
200000cells. - Every cell is either
0or1.