Overview & Concept
Depth-First Search (DFS) is an essential graph traversal algorithm that explores as deeply as possible along each branch before backtracking. It is naturally implemented via recursion or an explicit LIFO stack and is the foundation for cycle detection, topological sorting, connected components, and maze generation.
How It Works
LIFO Exploration: Traverses along an edge branch until reaching a dead end, then backtracks to the most recent branching node.
Visited Set Tracking: Maintains visited nodes to prevent cycles.
Discovery and Finish Timestamps: Records entry and exit times for topological ordering.
Low Memory Footprint: Memory consumption is bounded by the maximum depth of the graph: O(depth).
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(V + E) | O(V + E) | O(V + E) | O(V) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure DFS(graph, vertex):
mark vertex as visited
for neighbor in graph.adjacent(vertex):
if neighbor is not visited:
DFS(graph, neighbor)- Parenthesis Theorem: For any two nodes u and v, their active discovery/finish intervals are either completely disjoint or one is nested inside the other.
Advantages & Disadvantages
Key Advantages
- •Low memory consumption: O(h) space where h is graph depth (much less than BFS on wide graphs).
- •Powers topological sort, strongly connected components (Kosaraju, Tarjan), and cycle detection.
Trade-offs & Limitations
- •Does not find the shortest path.
- •Can get trapped in deep branches or stack overflow without depth limiting on deep graphs.
Real-World Applications
Topological Build Sorting
Build tools (Make, Webpack) ordering tasks with prerequisite dependencies.
Maze Solving & Generation
Depth-first backtracking generating and navigating mazes.
Cycle Detection in Dependency Graphs
Detecting circular import dependencies in module loaders.
Decision Guide: When to Use
Ideal Scenarios
- ✓When detecting cycles or performing topological sorting.
- ✓When searching all possible game paths (chess, tic-tac-toe) or solving puzzles.
Consider Alternatives When
- ✕When shortest path routing is required (use BFS or Dijkstra).
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.