The Number Of Islands
Given an m x n
2D binary grid
grid which represents a map of '1'
s (land) and '0'
s (water), return 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 all surrounded by water.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is '0' or '1'.
Solutions
Time Complexity: (N*M)
The time complexity of this algorithm is O(NM), where N is the number of rows and M is the number of columns in the grid. This is because the algorithm visits each cell in the grid once in the outer loop, and for each cell that contains a ‘1’, it calls the ResetLand method, which takes O(NM) time in the worst case (when all cells in the grid contain a ‘1’).
Space Complexity: (N*M)
The space complexity of this algorithm is O(NM) as well, due to the recursive call stack of the ResetLand method. In the worst case, when all cells in the grid contain a ‘1’, the maximum depth of the recursive call stack will be NM.
Last updated