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
Graph0①1②2⑤3③4④dead 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#

  • Time Complexity: O(V + E), since it visits every vertex and edge once
  • Space Complexity: O(V) for the recursion stack (or an explicit stack)

Interactive Lab#

Let's take the example in this visualization: six vertices A to F joined by nine edges, source A, target E. Press play and watch the stack rather than the graph. A pushes B and D; B is popped first and pushes C and E. Then C is popped, and every neighbour of C is already visited, so the frame returns with nothing to show for itself. That is the backtrack: the amber call-stack chain retracts to B before the traversal moves on and finds E.


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 (counting 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

What to Remember#

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.