"Here's the secret that makes the Trees and Graphs tracks feel easy: DFS and BFS share one traversal skeleton. Swap the frontier from a stack to a queue and depth flips into breadth. Visited timing and duplicate handling complete it, but the container is the switch that changes its temperament."
The Frontier
Whenever you explore a structure — a maze, a tree, a network — you keep a frontier: the set of places you've discovered but not yet explored. The algorithm is always the same shape: take a place from the frontier, look at it, add its undiscovered neighbors to the frontier, repeat until the frontier is empty. The entire character of the search comes down to one question: which place do you take next?
The Single Swap That Changes Everything
That "which next?" is answered by the data structure holding the frontier:
- Frontier is a stack → you take the most recently discovered place → you keep plunging down the newest path → depth-first search (DFS). You go as deep as possible before backing up.
- Frontier is a queue → you take the oldest discovered place → you finish everything close before going further → breadth-first search (BFS). You sweep outward in rings, level by level.
The frontier container is the central difference, but changing one method call is not always the whole implementation. Neighbor order, discovery timing, duplicate suppression, and parent or distance recording affect correctness, efficiency, and the exact traversal order.
Why Each One Matters
BFS explores in order of distance, so it naturally finds the shortest path (in number of steps) — which is why it's the backbone of the Graphs track. DFS dives deep, which suits exhaustively exploring all possibilities, detecting cycles, and topological ordering — and it's exactly the backtracking you'll meet in the Recursion track (where the stack is the call stack itself). The same stack/queue duality you just learned is the engine under both trees and graphs. You've already built the hard part.
Pippa's Confession
explore function and swapped its stack for a queue; depth flipped into breadth in front of me, and the two fused into one idea I could never un-see. It's my favorite kind of lesson—not two facts to memorize, but one fact that dissolves the need to memorize. The frontier chooses the traversal's temperament; visited timing and duplicate handling turn that skeleton into a complete algorithm.