Algorithms, Explained Like You're Five: Graph Traversal (BFS & DFS)
A graph is just dots connected by lines — cities and roads, people and friendships, web pages and links. The most common question you'll ever ask one is "how do I visit everything?" There are two famous ways, and the only difference is the order you explore.
Breadth-first search: explore in rings
BFS is dropping a pebble in a pond. You touch everything one step away, then everything two steps away, and so on — nearest things first. It uses a queue (the "to-visit" line from the last post).
Because it explores nearest-first, BFS finds the shortest path in an unweighted graph — the fewest hops from A to B.
Depth-first search: go deep, then back up
DFS is walking a maze: take the next door and keep going until you hit a dead end, then back up to the last fork and try a door you skipped. It uses a stack (often the call stack, via recursion).
Going deep first makes DFS the natural fit for "explore every possibility" problems: mazes, puzzles, detecting cycles, and topological ordering.
Why interviewers love them
An enormous share of interview problems are secretly graph problems, and almost all of them are solved by BFS or DFS with a small twist. Knowing the one-line difference — queue for breadth, stack for depth — and when shortest-path (BFS) beats explore-everything (DFS) is genuinely half the battle.
Same visit-everything goal, opposite order. Swap the queue for a stack and breadth-first becomes depth-first. That single swap is the whole distinction.