Stage 1 · Code
Graphs & Backtracking
Graph Drills
Connected components, cycle detection, matrix traversal, and backtracking — train the patterns that separate graph-solvers from the rest.
How to Drill Graphs
Graph problems are really four decisions: adjacency representation (list vs matrix), traversal choice (DFS vs BFS), visited tracking (set vs in-place mutation), and state accumulation (count, path, distance). Do those four quickly and the algorithm writes itself.
When the question asks 'can you reach?' or 'how many components?', DFS is simpler. When it asks 'shortest path' or 'minimum steps', BFS guarantees optimality on unweighted graphs.
Graph Patterns
| Pattern | Algorithm | Tells |
|---|---|---|
| Connected Components | DFS/BFS on every unvisited node | Number of islands, friend circles |
| Cycle Detection | DFS with visiting/safe states OR union-find | Course schedule dependency graph |
| Matrix Traversal | 4-directional DFS/BFS with bounds check | Pacific Atlantic water flow, rotten oranges |
| Topological Sort | Kahn's algorithm (in-degree queue) | Build order, task scheduling |
| Shortest Path (unweighted) | BFS level-order | Word ladder, nearest exit |
| Backtracking Search | DFS + prune on constraint violation | N-Queens, word search |
Problems
Key Points
- Visited is everything — forgot visited = infinite loop. Use in-place mutation for grids, hash map for cloned nodes.
- BFS for minimum moves — unweighted shortest paths need a queue, not recursion.
- Cycle detection in directed graphs — use three-colour DFS (white/gray/black) or Kahn's in-degree.
- Matrix = implicit graph — neighbours are 4 (or 8) directional offsets, bounds-check first.
- Backtracking needs pruning — fail fast when constraints violate, restore state after exploring.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.