Command Palette

Search for a command to run...

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.

Intermediate 4 lessons 8 problems ~45 min of lessons

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

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Counting connected components on a grid by sinking each island.

  2. The paint-bucket tool: DFS over same-coloured neighbours.

  3. A DFS that returns a value: the size of the region it explored.

  4. Components when the graph is given as an adjacency matrix.

  5. Mark the survivors from the border, then flip everything else.

  6. Two reverse searches from two borders, then intersect.

  7. Path enumeration on a DAG with add / recurse / remove.

  8. Reachability from one node: is every node visited?