Graphs
Representations: adjacency list graph[u] = [v, …], or an implicit grid (4 neighbours).
| Need | Tool |
|---|---|
| Connected components / flood fill | DFS or BFS, or Union-Find |
| Shortest path, unweighted | BFS (multi-source: seed the queue with all sources) |
| Ordering with dependencies / cycle in DAG | Topological sort (Kahn's BFS on in-degrees) |
| Dynamic connectivity, "redundant edge" | Union-Find (path compression + union by size) |
# grid BFS
q, seen = deque([(sr, sc)]), {(sr, sc)}
while q:
r, c = q.popleft()
for nr, nc in ((r+1,c), (r-1,c), (r,c+1), (r,c-1)):
if 0 <= nr < R and 0 <= nc < C and (nr, nc) not in seen and grid[nr][nc] == OPEN:
seen.add((nr, nc)); q.append((nr, nc))
# union-find
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb: return False
parent[ra] = rb; return True
Problems
Showing 37 of 37