This is LeetCode #200: Number of Islands — the most classic graph problem and a top interview question! 🏝️
💡 Think of it like this: You're looking at a map from above. There's land ("1") and water ("0"). An island is a group of land cells that are connected up/down/left/right. How many separate islands do you see?
The Algorithm — DFS (Depth-First Search):
💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀
Complexity: Time O(rows × cols) — visit every cell once. Space O(rows × cols) — recursion stack in worst case.
def numIslands(grid):
count = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == '1': # Found new island!
count += 1
dfs(grid, r, c) # Sink the whole island
return count
def dfs(grid, r, c):
# Out of bounds or water? Stop.
if r < 0 or c < 0 or r >= len(grid) or c >= len(grid[0]) or grid[r][c] != '1':
return
grid[r][c] = '0' # Mark as visited (sink it)
dfs(grid, r+1, c) # Down
dfs(grid, r-1, c) # Up
dfs(grid, r, c+1) # Right
dfs(grid, r, c-1) # Left
numIslands(grid)
3