Browse curriculum

Depth-First Search (DFS)

Depth-first search (DFS) traverses a graph by exploring as deep as possible along each branch before backtracking, using a stack or recursion.

START

Stack (LIFO)

A ◂ top

Visit order

Nothing visited yet

 

Start at A. Push it onto the stack.

Next

Pop A and mark it visited — position 1 in the order.

Start

Edges

Intuition

Imagine solving a maze.

You follow a path until you hit a dead end, then you backtrack to the last junction and try a different path.

DFS explores as far as possible along each branch before backtracking. It dives deep!

Concept

Depth-First Search (DFS) is a graph traversal algorithm that explores as deep as possible along each branch before backtracking.

It uses a Stack (Last-In-First-Out) data structure, or implicit recursion stack.

How it Works

Algorithm Steps:
  1. Push the starting node to Stack (or call recursive function).
  2. Mark node as visited.
  3. Process node.
  4. For every unvisited neighbor:
  5. Recursively call DFS (or push to Stack).

Step-by-Step Breakdown

Watch the visualization above:

  • Solid blue node: The node just popped and visited.
  • Pale blue node with a blue outline: On the stack, not yet visited.
  • Green node: Visited.
  • Stack (LIFO) panel: The last entry is the top and is popped next. A red entry was already visited by another branch and is discarded when popped.

When to Use

Use DFS when:

  • Solving puzzles with valid solutions (mazes, sudoku).
  • Detecting cycles in a graph.
  • Checking if a graph is bipartite.
  • Topological sorting.
  • Finding strongly connected components.

When NOT to Use

  • Shortest Path: DFS does NOT guarantee the shortest path. It might go down a very long rabbit hole first.
  • Stack Overflow: Deep recursion on very large graphs can cause stack overflow errors.

How to Identify

Problems asking to "visit all nodes", "find any path", "detect cycle", or "backtracking" usually imply DFS.

Preparing for interviews? This topic is also taught as a pattern:

Introduction to DFS

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

Why use a Stack for DFS?

A Stack ensures LIFO (Last-In-First-Out) order, which forces the algorithm to explore as deep as possible before backtracking.


What is Backtracking in DFS?

Backtracking is the process of returning to a previous node when the current path has no more unvisited neighbors.


DFS Applications?

Solving puzzles (mazes), cycle detection, finding connected components, and topological sorting.