Graphs
Graph Traversal (DFS & BFS)
Master Graph search: Depth-First Search (DFS) stack execution, Breadth-First Search (BFS) level-order traversal, and Connected Components.
Last Updated: August 2, 2026
•
18 min read
1. Introduction
What is Graph Traversal?
Graph Traversal is the process of visiting (checking and/or updating) each vertex in a graph systematically. The two fundamental search strategies are Depth-First Search (DFS) and Breadth-First Search (BFS).Why study them?
Most graph problems are variants of traversal. Tracing connectivity, checking cycles, finding connected islands, and pathfinding are built on top of DFS and BFS traversal foundations.Where is it Used?
2. Mental Models
DFS: The Labyrinth Explorer
Imagine walking through a dark labyrinth holding a string:visited set) to avoid walking in circles.BFS: Ripple in a Pond
Imagine throwing a stone into a still pond:3. Core Traversals & Implementations
Both algorithms require a visited container to prevent visiting nodes repeatedly in graphs with cycle paths:
4. Visual Expansion Trace
Comparing DFS vs BFS traversal starting from node 0 on the graph 0 -> 1 -> 3 and 0 -> 2:
DFS Order: 0 -> 1 -> 3 -> 2
DFS dives deep along path 0 -> 1 -> 3 first, backtracks to 0, and then visits 2.
BFS Order: 0 -> 1 -> 2 -> 3
BFS visits all immediate neighbors of 0 (1 and 2) first, then visits the neighbors of 1 (3).
5. Real-World Examples
6. Interview Perspective
How Interviewers Ask This Topic
Interviewers test traversal choice selection:originalNode -> clonedNode to avoid cyclic loops.Common Mistakes
Warning: 1. Forgetting Visited Tags: Omitting
visited validation in cyclic graphs. Without a visited set, the traversal will bounce back and forth between connected nodes forever, causing a stack overflow (in DFS) or infinite loop (in BFS).> 2. BFS Visited Flag Timing: Marking nodes as visited after popping from the queue instead of before pushing. In BFS, you must mark a node as visited as soon as you push it onto the queue. Otherwise, a node might be pushed multiple times by different neighbors, leading to duplicate queue additions.
7. Summary
O(V + E), Space: O(V) (for recursive stack).O(V + E), Space: O(V) (for queue).8. Quiz
Question 1: Why does DFS require less memory than BFS on wide, shallow graphs?
Answer: Because BFS queues up all nodes at a given level. On wide graphs, a level might containO(V) elements, consuming high queue memory. DFS only stores the current depth path on the recursion stack.