Skip to content
StackDecode
GraphsAnimated

Depth-First Search (DFS)

Go as deep as possible, then backtrack.

Time

O(V + E)

Extra space

O(V)

Use it for

Connectivity, cycles, topological order.

How it works

  1. Start at the chosen node and push it on a stack.
  2. Pop a node, visit it if new, and push its unvisited neighbours.
  3. Because the stack is last-in-first-out, the search keeps going deeper along one path before backing up.
  4. Useful for connectivity, cycle detection and ordering.

Watch it run

Loading animation…