Medium
Number of Islands
👶 The 5-Year-Old Summary
You have a map of the ocean (0s) and land (1s). Count how many islands (connected land pieces)! Connected means touching up, down, left, or right - no diagonals!
🎮 Interactive Visualizer
🧠The Brain Hack
DFS flood fill! When you find land, "sink" it (turn to water) and recursively sink all connected land. Each time you start a new DFS = new island!
💻 The Clean Solution
def num_islands(grid):
if not grid: return 0
def dfs(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] == '0'):
return
# "Sink" this land
grid[r][c] = '0'
# Visit all 4 directions
dfs(r+1, c)
dfs(r-1, c)
dfs(r, c+1)
dfs(r, c-1)
count = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == '1':
count += 1
dfs(r, c) # Sink the whole island
return count
# 1 1 1 0 0
# 1 1 0 0 1
# 0 0 0 1 1
# 0 0 0 0 0
# Answer: 3 islands
Time: O(m × n)
Space: O(m × n) worst case