Skip to main content

DFS

What DFS means, when exploring one path deeply makes more sense, and why recursion shows up with it so often.

Andrews Ribeiro

Andrews Ribeiro

Founder & Engineer

What it is

DFS means depth-first search.

It is a traversal strategy that goes deep on one path before backing up to try another one.

When to use it

It usually appears when you want to:

  • explore a component
  • do backtracking
  • traverse a tree or graph with an implicit or explicit stack

Recursion appears often because the “go in, go deeper, come back” pattern fits naturally.

Common mistake

The classic mistake is reducing DFS to recursion.

Recursion is a common implementation.

The core idea is the exploration order, not the syntax.

Better question

Before using it, ask:

  1. do I gain something by exploring one path all the way before returning?
  2. am I enumerating possibilities?
  3. does a stack describe this flow better?

Keep exploring