Explore recursive DFS with call stack frames and backtracking visualization. Watch how the recursion dives deep, pauses at each level, and backtracks when no more neighbors exist. Step through the execution to see the complete picture.
Depth-First Search (DFS) is a graph traversal algorithm that explores as far as possible along each branch before backtracking. It uses a stack — either explicitly or via the call stack during recursion — to maintain the frontier of unexplored nodes. DFS is fundamental to many graph algorithms including topological sorting, cycle detection, and connectivity analysis.
DFS on Tree — Example 1
[ ]
[ ]
DFS on Graph — Example 2
[ ]
[ ]
Algorithm & Pseudocode
| Aspect | Complexity |
|---|---|
| Time | O(V + E) |
| Space (Recursive) | O(V) — call stack depth |
| Space (Iterative) | O(V) — explicit stack |
Implementation
1. Iterative DFS — Manual Stack (lines 6–19): Declares a plain int stack[] with top = -1. Push increments top before assigning; pop reads then decrements. Loop runs while top ≥ 0. Neighbors are pushed in reverse order (line 15) so the lowest-indexed neighbor surfaces on the next pop, ensuring left-to-right traversal.
2. Recursive DFS — Call Stack (lines 22–30): The OS call stack is the implicit DFS stack. Mark node visited, print it, then iterate neighbors. Each unvisited neighbor triggers a recursive call — diving deeper. When the call returns on line 28, the CPU pops the frame and continues the for-loop: that is the backtrack. Deep graphs can overflow the C stack (default ~1–8 MB).
3. Adjacency Matrix (lines 33–40): A 2-D array where adj[u][v] = 1 means an undirected edge exists. Simple to write; costs O(V²) space. Swap for an adjacency list on large sparse graphs to save memory.
4. Time & Space Complexity: Both variants run in O(V + E) — each node is visited once and each edge checked once. Space is O(V) for visited array plus O(V) worst-case stack depth. The matrix itself adds O(V²) storage regardless of edge count.