Grid traversal (islands)
Check bounds, check seen, mark, then go four ways.
A 2D grid where cells connect up, down, left and right, and you count or measure connected regions.
Trigger words
island
flood fill
connected cells
surrounded regions
max area
4-directionally adjacent
from collections import deque
def num_islands(grid):
rows, cols = len(grid), len(grid[0])
visited = set()
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != '1' or (r, c) in visited:
continue
islands += 1 # new land: one more island
visited.add((r, c)) # mark as soon as you add it
queue = deque([(r, c)])
while queue:
row, col = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = row + dr, col + dc
if not (0 <= nr < rows and 0 <= nc < cols):
continue # off the grid
if grid[nr][nc] == '1' and (nr, nc) not in visited:
visited.add((nr, nc))
queue.append((nr, nc))
return islandsSpot it when
- 'Number of islands', 'max area', 'surrounded regions'.
- Flood fill.
Remember
- Mark a cell visited when you add it to the queue, not when you pop it, so it is never added twice.
- A visited set leaves the input untouched; overwriting '1' with '0' saves memory, but ask the interviewer first.
- BFS avoids Python's recursion limit on large grids; a recursive DFS is fine for small grids.
How problems bend it
- Largest island: Count the cells you pop for each island and keep the maximum.
- Cells connected to the border: Start the search from every border cell first, then look at what was never reached.
- Recursive DFS instead of a queue: dfs(r, c): return if out of bounds, not land, or seen; mark it; call dfs on the four neighbours.

