Visualizer is loading, please wait...

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

1. Mark Node VisitedMark current node as visited and record discovery timestamp.
2. Traverse NeighborsIterate unvisited neighbors; recursively call DFS on each.
3. Dead-End BacktrackWhen all neighbors are visited, record finish timestamp and backtrack to parent.
4. Check ComponentsIf unvisited nodes remain in the graph, start new DFS pass to find all connected components.

Asymptotic Complexity Analysis

MetricBest CaseAverage CaseWorst CaseSpace Complexity
Complexity BoundO(V + E)O(V + E)O(V + E)O(V)
ExplanationOptimal 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

Algorithm Logic
procedure DFS(graph, vertex):
  mark vertex as visited
  for neighbor in graph.adjacent(vertex):
    if neighbor is not visited:
      DFS(graph, neighbor)
Algorithmic Invariants
  • 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.
Correctness Guarantee: Invariants hold true prior to loop entry, are preserved during every iteration, and guarantee correct post-condition upon termination.

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).

Compare trade-offs and complexity across complementary tools in AlgoViz.