What Is DFS?

Depth-First Search (DFS) explores a graph or tree by going as deep as possible down one path before backtracking and trying another.

Think of navigating a maze: you pick a corridor and walk until you hit a dead end, then backtrack to the last junction and try a different turn.


How It Works

Starting from a source node:

  1. Mark the current node as visited
  2. Explore each unvisited neighbour recursively (or via a stack)
  3. When all neighbours are visited, backtrack
Graph01234dead end↩ backtrackDFS from 0① Visit 0② Visit 1 (go deep)③ Visit 3 (dead end) ↩ backtrack to 1④ Visit 4 (dead end) ↩ backtrack to 0⑤ Visit 2 (dead end)Visit order:0 → 1 → 3 → 4 → 2

Implementation

Loading...
  • Time Complexity: O(V + E) — visits every vertex and edge once
  • Space Complexity: O(V) — recursion stack depth (or explicit stack)

Interactive Lab

Watch DFS push neighbours onto the call stack and backtrack when a dead end is reached.

Simulation not available for this algorithm.

DFS on Trees

On a binary tree, DFS naturally produces three orderings based on when you process the root:

OrderProcess RootCommon Use
Pre-orderBefore childrenCopying a tree
In-orderBetween childrenSorted output from BST
Post-orderAfter childrenDeleting a tree, expression evaluation

Key Applications

  • Cycle detection in directed/undirected graphs
  • Topological sort (dependency ordering)
  • Path finding between two nodes
  • Connected components — count isolated regions
  • Solving puzzles (mazes, Sudoku) via backtracking

DFS vs BFS — When to Use Which

GoalChoose
Find any pathDFS (simpler code)
Find shortest path (unweighted)BFS
Explore deep hierarchies (file system)DFS
Level-by-level traversalBFS

Key Takeaway

DFS is your go-to when you need to explore all reachable states. Its recursive nature maps cleanly onto tree/graph structures. Watch out for cycles in graphs — always track visited nodes.