Graphs (BFS, DFS, Topological Sort)
Signal: grids of cells, networks of cities, courses with prerequisites, word transformations, "connected", "reachable", "shortest number of steps", "order respecting dependencies".
Core idea: model the problem as nodes and edges, then pick the traversal:
| Need | Use |
|---|---|
| Visit everything connected / count components | DFS or BFS |
| Shortest path in an unweighted graph (min steps) | BFS (the first time you reach a node is via a shortest path) |
| Spreading from many sources at once (rot, fire, distance to nearest X) | Multi-source BFS |
| Ordering with dependencies, cycle detection in a directed graph | Topological sort (Kahn's BFS or DFS colors) |
| Weighted shortest paths | Dijkstra (heap), with non-negative weights |
Templates
python
from collections import deque
# Grid BFS (4-directional)
def bfs(grid, sr, sc):
R, C = len(grid), len(grid[0])
q, seen = deque([(sr, sc)]), {(sr, sc)}
while q:
r, c = q.popleft()
for dr, dc in ((1,0), (-1,0), (0,1), (0,-1)):
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C and (nr, nc) not in seen and grid[nr][nc] == 1:
seen.add((nr, nc)); q.append((nr, nc))
# Kahn's topological sort
def topo(n, edges): # edges: u -> v means u before v
adj = [[] for _ in range(n)]; indeg = [0] * n
for u, v in edges: adj[u].append(v); indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0); order = []
while q:
u = q.popleft(); order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return order if len(order) == n else None # None → cycleMark visited when you enqueue, not when you dequeue
Otherwise the same node can be enqueued many times, which blows up time and memory on dense graphs and grids.