Graph Traversal: BFS & DFS
Graph Theory
Chapter 3 · Graph Traversal: BFS & DFS
Every algorithm this course covers from here on — cycle detection, topological sort, shortest paths — is a variation on one of two ways to systematically visit every reachable vertex in a graph. Both visit the same vertices in the end; the order they visit them in is what makes each one suited to genuinely different problems.
Breadth-First Search (BFS) — Level by Level
Depth-First Search (DFS) — Follow One Path to the End
A Worked Comparison: Genuinely Different Orders
A branching graph: A connects to B and C; B connects to D and E; C connects to F.
| Traversal | Visit order from A |
|---|---|
| BFS | A, B, C, D, E, F — both level-1 vertices (B, C) before any level-2 vertex |
| DFS | A, B, D, E, C, F — B's entire branch (D, E) fully explored before C is even touched |
Complexity — And Why the Representation Choice Matters
Real Use Cases
| Traversal | Used for |
|---|---|
| BFS | Shortest path in unweighted graphs, "nearest" queries, level-order/web-crawling-by-distance |
| DFS | Cycle detection (Chapter 4), topological sort (Chapter 5), path-existence/maze-solving, finding connected components |
Both Traversals in Code
Hands-On Exercises
A graph has vertex 1 connected to 2 and 3; 2 connected to 4; 3 connected to 5 and 6. Trace the BFS visit order starting from vertex 1, following this chapter's own level-by-level method.
Using the exact same graph as Exercise 1, trace the DFS visit order starting from vertex 1 (visiting each vertex's neighbors in the order given: for vertex 1, visit 2 before 3; for vertex 3, visit 5 before 6). Compare the resulting order directly against Exercise 1's BFS order.
Explain, in your own words, why BFS is guaranteed to find the shortest (fewest-edge) path to every reachable vertex in an unweighted graph, while DFS gives no such guarantee — grounding your answer in this chapter's own level-by-level vs. dive-then-backtrack distinction.
📄 View solutionChapter 3 Quick Reference
- BFS: queue-based, visits level by level — guarantees the shortest (fewest-edge) path in unweighted graphs
- DFS: stack/recursion-based, dives down one branch fully before backtracking
- Both are Θ(V+E) on an adjacency list — but O(V²) on an adjacency matrix, since Chapter 2's own representation choice directly affects traversal speed
- BFS → shortest unweighted paths, nearest-neighbor queries; DFS → cycle detection, topological sort, path existence, connected components
- Next chapter: Connectivity and cycle detection