Optimal Breadth-First Search (BFS) / Depth-First Search (DFS) Approach:
- Iterate through the grid; when unvisited land ('1') is found, increment island count and sink the connected land mass using DFS/BFS.
def num_islands(grid: list[list[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
count = 0
def dfs(r, c):
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
dfs(r + 1, c)
dfs(r - 1, c)
dfs(r, c + 1)
dfs(r, c - 1)
for r in range(rows):
for c in range(cols):
if grid[r][c] == '1':
count += 1
dfs(r, c)
return count
Complexity & Key Logic:
- Time Complexity: O(M * N) where M is rows and N is columns; each cell visited a constant number of times.
- Space Complexity: O(M * N) worst-case recursion stack if entire grid is filled with land.
- Algorithm Details:
- Mutate grid in-place (grid[r][c] = '0') to eliminate extra visited set memory.
- Explore 4-directionally (up, down, left, right) until boundary or water reached.