5. Graphs & Dynamic Programming
Graphs: Grid BFS/DFS, Cycle Detection & Topological Sort
Model networks, grids, and course prerequisites cleanly with adjacency lists in Python: traverse graphs safely with visited sets, find shortest unweighted paths via BFS, and order dependencies with Kahn's Topological Sort.
- Represent directed and undirected graphs cleanly using defaultdict(list)
- Traverse graphs and 2D grids without infinite loops using a visited set
- Order prerequisite tasks and detect dependency cycles using Kahn's BFS Topological Sort
Unlike trees, graphs can have cycles, multiple paths between two nodes, and disconnected components. One missing visited check will send your traversal into an infinite loop (or RecursionError)!
Why It Matters: Graphs Model Every Real Network
From social graphs and road maps to package managers (pip / npm dependencies) and 2D game grids, graph problems all run in O(V + E) time (vertices + edges) when represented with an adjacency list (defaultdict(list)) instead of an O(V²) adjacency matrix.
Building an Adjacency List in 3 Lines
from collections import defaultdict
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u) # Omit this line for directed graphs!For 2D grids (islands, mazes, shortest paths), treat each cell (r, c) as a node whose 4 neighbors are (r + dr, c + dc) for (dr, dc) in ((1, 0), (-1, 0), (0, 1), (0, -1))—no adjacency list needed!
Pattern 1: Grid DFS / BFS & The visited Timing Rule
- Use DFS when counting connected components (Number of Islands), flood-filling regions, or checking reachability.
- Use BFS (
deque) whenever you need the shortest path (minimum steps) on an unweighted graph or grid, because BFS explores outward layer by layer (dist = 0, 1, 2, ...).
If you add (nr, nc) to visited only after popping it from the deque, multiple neighbors at distance d will push the exact same cell into the queue—causing duplicate work and exponential queue blow-up on grids! Mark visited.add((nr, nc)) immediately before q.append(...).
Pattern 2: Kahn's Topological Sort (Prerequisites & Cycle Detection)
Course 0
indegree = 0 (Start)
Course 3
indegree: 2 → 1 → 0
Start with indegree == 0 nodes in a deque; removing each node unlocks downstream courses until none remain (or a cycle blocks completion).
Given num_courses tasks with prerequisite edges (course, prereq) meaning prereq -> course, Kahn's Algorithm produces a valid linear build/study order—or detects a cycle:
- Compute
indegree[v](how many prerequisitesvstill waits on). - Enqueue every node with
indegree == 0(no remaining prerequisites). - Pop
cur, append toorder, decrementindegree[nxt]for each neighbor, and enqueuenxtifindegree[nxt] == 0. - Cycle check: If
len(order) < num_courses, at least one cycle prevented nodes from ever reachingindegree == 0!
Step-by-Step Dry-Run Trace: course_order(4, [(1, 0), (2, 0), (3, 1), (3, 2)])
Edges: 0 -> 1, 0 -> 2, 1 -> 3, 2 -> 3. Initial indegree = [0, 1, 1, 2].
| Step | Queue Start | Popped (cur) | Neighbors Decremented | Newly 0 Enqueued | order After Step |
|---|---|---|---|---|---|
| Init | [0] | — | — | — | [] |
| 1 | [0] | 0 | indegree[1]=0, indegree[2]=0 | 1, 2 | [0] |
| 2 | [1, 2] | 1 | indegree[3]=1 | None | [0, 1] |
| 3 | [2] | 2 | indegree[3]=0 | 3 | [0, 1, 2] |
| 4 | [3] | 3 | None | — | [0, 1, 2, 3] |
len(order) == 4 == num_courses → valid schedule! Now imagine edges (0, 1) and (1, 0): indegree = [1, 1], the queue starts empty, and len(order) == 0 < 2 immediately detects the cycle!
Edge Cases to Always Guard Against
- Empty grid (
grid = []orgrid = [[]]): Guardif not grid or not grid[0]: return 0. - Disconnected nodes with 0 edges in Topological Sort: Initializing
q = deque(i for i in range(num_courses) if indegree[i] == 0)ensures isolated courses are included automatically. - Mutating the input grid vs keeping a
visitedset: Overwritinggrid[r][c] = "0"savesO(R·C)space, whilevisited = set()keeps the caller's input untouched.
On a 500 × 500 grid of all "1"s, recursive DFS can hit Python's 1,000-frame recursion limit! For large production grids, convert DFS to an iterative stack (stack = [(r, c)]) or BFS (deque).
Pattern Recognition: Which Graph Algorithm?
| Problem Signal | Best Algorithm | Complexity |
|---|---|---|
| Count connected components / flood fill | DFS or BFS with visited | O(V + E) |
| Shortest path in unweighted graph or grid | BFS (deque) | O(V + E) |
| Course schedule, task dependencies, cycle in directed graph | Kahn's Topological Sort | O(V + E) |
| Shortest path with positive edge weights | Dijkstra (heapq) (see Lesson 15!) | O((V + E) log V) |
Try It Yourself in the Playground
Test Number of Islands (Grid DFS) and Kahn's Topological Sort (Course Prerequisites & Cycle Detection) right below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why should BFS mark a node as visited at the moment it is pushed onto the deque rather than when it is popped?
Quick Checkpoints
In Kahn's Topological Sort algorithm, how do you know the directed graph contains a dependency cycle (impossible schedule)?
Which traversal guarantees finding the shortest path (fewest steps) in an unweighted graph or 2D grid?
What is the time complexity of traversing a graph with V vertices and E edges represented as an adjacency list?