Intuition
A graph is a set of nodes joined by edges: cities and roads, people and friendships, web pages and links. Traversal answers “what can I reach from here?”
The two classic strategies differ in what they do next:
- Breadth-first search (BFS) is a ripple in a pond. It visits everything one edge away, then everything two edges away, and so on.
- Depth-first search (DFS) is exploring a maze with one hand on the wall. It follows one path as far as it goes, then backs up to the last fork.
How it works
Both keep a list of nodes waiting to be visited and a set of nodes already seen:
- Put the start node in the waiting list.
- Take a node out and visit it.
- Add each of its unseen neighbours to the waiting list.
- Repeat until the list is empty.
The only difference is which node comes out next. BFS uses a queue (first in, first out), so the oldest discovery is visited next. DFS uses a stack (last in, first out), so the newest discovery is visited next. That one choice produces completely different orders.
Complexity
Each node enters the waiting list a bounded number of times and each edge is checked from both ends, so both searches take O(V + E) time for V nodes and E edges. Both need O(V) memory for the seen set and the waiting list.
When to use which
| Need | Use |
|---|---|
| Fewest-edge path in an unweighted graph | BFS |
| Everything within k steps (e.g. friends of friends) | BFS |
| Detecting cycles, topological order, maze solving | DFS |
| Shortest path when edges have weights | Dijkstra |
Common mistakes
- No seen set. Without it, any cycle makes the search loop forever.
- Marking seen too late in BFS. Mark a node when you add it to the queue, not when you visit it, or it can be queued many times.
- Assuming DFS finds shortest paths. It finds a path, often a long one.
- Recursing too deep. Recursive DFS on a long chain can overflow the call stack; an explicit stack, as in the code here, can’t.
Check yourself
Check yourself
Which search finds the path with the fewest edges in an unweighted graph?
BFS reaches every node one edge away before any node two edges away, so the first time it reaches a node is by a fewest-edge path.
Check yourself
Which pairing is right?
A queue serves the oldest discovery first, which spreads outward. A stack serves the newest first, which dives deeper.
Sources
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, sections 22.2 and 22.3 (3rd edition).
- Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition, section 4.1.
Finished this page?
Your list