Module 22
Depth-First Search
Go deep, then back up: the DFS template, connected components, flood fill, working inward from the border, and enumerating paths.
Depth-first search follows one path as far as it can, then backs up to the last junction and tries the next branch. It's the natural fit for "explore everything connected to this" questions: counting islands, filling regions, checking whether all rooms can be reached, and listing every path.
DFS doesn't give shortest paths (that's BFS), but it's shorter to write, uses memory proportional to the depth, and its enter/leave timing is what cycle detection and topological sort are built on in the next two modules.
Best after: Graph Fundamentals, Recursion
Part 1
Learn the ideas
- 22.1The DFS TemplateMark the node, then recurse into every unvisited neighbour. Iteratively, the same thing with an explicit stack.12 min
- 22.2Components and Flood FillLoop over every node; each time you find an unvisited one, start a DFS that marks its whole component. The number of starts is the number of components.12 min
- 22.3Working Inward from the BorderWhen the question is "which cells can reach the edge?", reverse it: start DFS from the edge and mark everything reachable.10 min
- 22.4Enumerating Paths: DFS + BacktrackingTo list every path, keep the current path, add a node before recursing and remove it after. In a DAG no visited set is needed.10 min
Part 2
Solve the problems
In order of difficulty. Each one shows the pattern it teaches.
Counting connected components on a grid by sinking each island.
The paint-bucket tool: DFS over same-coloured neighbours.
A DFS that returns a value: the size of the region it explored.
Components when the graph is given as an adjacency matrix.
Mark the survivors from the border, then flip everything else.
Two reverse searches from two borders, then intersect.
Path enumeration on a DAG with add / recurse / remove.
Reachability from one node: is every node visited?