Scan every cell; on land, count one island and recursively sink everything connected to it.
sink(r, c) turns a land cell to water and recurses into its four neighbours. Out-of-bounds or water cells return immediately. After the call, that entire island is gone from the grid and can't be counted twice.
Algorithm
count = 0.- For every cell
(r, c): if it's'1',count += 1and callsink(r, c). sink: return if out of bounds or not land; set to'0'; recurse to 4 neighbours.- Return
count.
- Time
- O(m · n)
- Space
- O(m · n)
Every cell is visited a constant number of times. Space is recursion depth in the worst case.
class Solution: def numIslands(self, grid: list[list[str]]) -> int: rows, cols = len(grid), len(grid[0]) count = 0 def sink(r: int, c: int) -> None: if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1": return grid[r][c] = "0" # mark visited by sinking the land sink(r + 1, c) sink(r - 1, c) sink(r, c + 1) sink(r, c - 1) for r in range(rows): for c in range(cols): if grid[r][c] == "1": count += 1 # new, never-seen island sink(r, c) # remove all of it return count