DFS Visualization: Depth-First Search on Your Own Graph

Depth-first search expands the deepest node in the frontier using a LIFO stack. It follows one branch as far as it can, then backtracks. It needs very little memory but may return a long path and can get lost in infinite spaces.

About this visualization

Depth-first search follows one branch as deep as it can and backs up only when it reaches a dead end, using a last-in-first-out stack. It needs little memory but can return long, expensive paths. Build a graph and watch the stack grow and shrink.

How it works

  1. Put the start node on a stack.
  2. Pop the top node; if it is the goal, stop. Otherwise push its unexplored neighbours.
  3. The most recently found node is always explored next, so the search plunges down one branch before trying another.

Formulas used

  • Time: O(bm)O(b^{m}) Space: O(b⋅m)O(b\cdot m)
  • mm = maximum depth of the search space

Worked example

On the 15-node binary tree with goal K, DFS expands A, B, D, H, I, E, J and then reaches K, visiting the left side first. BFS would have expanded A through J level by level. Both find A → B → E → K here, but DFS took a very different route to get there.

Enter these numbers in the simulator above to see every step.

Complexity and properties

Worst caseO(bm)O(b^{m})
SpaceO(b⋅m)O(b\cdot m)

Not optimal. Not complete in infinite or cyclic spaces unless it remembers explored nodes (as here).

When to use it

  • Finding any path or checking connectivity.
  • Topological sorting, cycle detection and maze solving.
  • Understanding memory-light search.

Frequently asked questions

What is the time complexity of DFS?

O(bm)O(b^{m}) time and O(b⋅m)O(b\cdot m) space in a tree, where m is the maximum depth; O(V+E)O(V + E) on a graph with an explored set.

Is DFS complete and optimal?

It is not optimal, and it is incomplete in infinite or cyclic spaces unless it remembers explored nodes.

What data structure does DFS use?

A stack — explicitly, or implicitly through recursion.