Island (Matrix Traversal)
DFS or BFS on a 2D grid. Four directions. One flood-fill. The outer loop handles disconnected islands — the inner DFS sinks each one entirely.
Nested loops count cells. Wrong. Flood-fill DFS counts connected components. Correct.
The insight: when the outer loop finds a '1', immediately DFS to mark ALL connected '1's as visited. The outer loop then never sees them again. Each cell is visited exactly once — O(m×n). Every island/connected-region problem on a matrix uses this exact outer-loop + flood-fill skeleton.
4-Directional Movement
Memorize these — they appear in every grid DFS/BFS problem.
dfs(r+1, c) # down dfs(r-1, c) # up dfs(r, c+1) # right dfs(r, c-1) # left
dirs = [(1,0),(-1,0),(0,1),(0,-1)]
for dr, dc in dirs:
dfs(r+dr, c+dc)if r<0 or r>=rows or c<0 or c>=cols: returnThen check cell value. Never check value before bounds — that's an IndexError.
8-directional (include diagonals): add
(1,1),(1,-1),(-1,1),(-1,-1) to dirs.The 3-Step Framework
Same 3 steps for every island / matrix traversal problem.
Iterate every (r,c) in the grid. When you find a trigger cell (e.g. '1' for land, 0 for island, old_color for flood fill), increment your counter and immediately flood-fill from that cell.
for r in range(rows):
for c in range(cols):
if grid[r][c] == '1': # unvisited land
islands += 1
dfs(r, c) # flood fillCheck bounds first. Then check if the cell is the target value. Then mark it (mutate in-place or add to visited set). Then recurse in all 4 directions. This order prevents IndexError and infinite loops.
def dfs(r, c):
if r<0 or r>=rows or c<0 or c>=cols: return # bounds
if grid[r][c] != '1': return # value
grid[r][c] = '0' # mark
dfs(r+1,c); dfs(r-1,c) # recurse
dfs(r,c+1); dfs(r,c-1)Closed islands, surrounded regions: first DFS from ALL border cells to eliminate border-touching components. Then do the normal outer-loop + DFS count on what remains. Two-pass approach — always O(m×n).
# Pass 1: eliminate border-connected
for r in range(rows):
for c in range(cols):
if on_border(r,c,rows,cols):
if grid[r][c] == target:
dfs(r, c, sink_value)
# Pass 2: count remaining
for r in range(rows):
for c in range(cols):
if grid[r][c] == target:
count += 1; dfs(r, c, visited_value)Pattern Recognition
Matrix + connectivity = Island pattern. Always.