Depth-First Search (DFS)

Back to Algorithms
Depth-First Search (DFS)
DFS is a graph traversal algorithm that explores as far as possible along each branch before backtracking.
Time Complexity (Worst)O(V + E)
Time Complexity (Average)O(V + E)
Space ComplexityO(V)
Primary Data StructureStack (LIFO) / Call Stack (Recursion)

Real-World Problems We Solve

01

Solving Mazes and Puzzles

The Problem: Navigating a complex labyrinth with branching corridors to find the exit.

How It Solves: DFS systematically tests a path to its very end. If it hits a dead-end, it backtracks to the last junction and tries the next path.

Real Example: AI solving a Sudoku grid or finding a path out of a 2D grid-based maze.
02

Topological Sorting (Task Dependency Scheduling)

The Problem: Determining the correct order of tasks when some tasks depend on others.

How It Solves: DFS runs until it finds a node with no dependencies, adds it to the output stack, and backtracks, naturally ordering prerequisites first.

Real Example: Compilers deciding file build compilation order, or course syllabus prerequisite engines.
03

Cycle Detection in Graphs

The Problem: Detecting circular dependencies which could cause infinite loops or deadlocks.

How It Solves: By keeping track of the recursion stack (back-edges), DFS can detect if a path points back to an ancestor node that is still currently being processed.

Real Example: Detecting cyclic dependencies in package management systems (like npm or pip).
04

Connected Components in Networks

The Problem: Grouping isolated clusters of nodes in a massive network structure.

How It Solves: Running DFS on an unvisited node will traverse every reachable node in its component. The number of times DFS is initiated equals the number of isolated networks.

Real Example: Identifying clusters of users in social groups or isolated islands in routing maps.