Depth-First Search
Imagine exploring a new city by picking one road and walking it to the very end — then backing up and trying the next road, and so on. You commit fully to each path before exploring alternatives. That's Depth-First Search (DFS).
Unlike BFS which spreads outward in rings, DFS plunges as deep as possible, then backtracks when it hits a dead end (a city with no unvisited neighbors).
Stack (or recursion)
DFS uses a stack — either explicitly or via the call stack of a recursive function. Cities are pushed when discovered and popped when their exploration is done. Recursion is the natural way to write DFS:
The iterative version replaces the call stack with an explicit stack data structure — useful when recursion depth could overflow.
Finding connected components
A map might have isolated islands — groups of cities with no roads between them. Run DFS from any unvisited city: every city you reach is in the same connected component (you can also track components with Union-Find). After DFS finishes, pick the next unvisited city and start a new DFS. Count how many times you restart to count components.
Cycle detection
During DFS, if you encounter a neighbor that's already been visited (and isn't your direct parent in the DFS tree), you've found a cycle — a circular route on the map. This is essential for detecting deadlocks, validating DAGs (used in topological sort), and more.
← → arrow keys to step · click elements to interact
DFS Traversal (Recursive & Iterative)
Complexity
DFS: Count Islands
Quick check
Continue reading