← capítulo

Depth-first search

Follow one branch as deep as it goes, then backtrack. BFS with a stack instead of a queue.

The stack makes it go deep

Watch it bore in

Orange = visiting · blue = recursion stack (active path) · green = backtracked. One long tendril, not a wave.

DFS wins on memory

Wide tree, 8191 nodes: DFS held 13, BFS held 4096 → 315× less.

What DFS is for

Two traps

Takeaway

BFS and DFS are a matched pair: one data-structure choice apart. Queue = breadth + shortest paths. Stack = depth + structure. Read every graph algorithm as "BFS or DFS, plus what?" Next: topological sort.