← Lessons

quiz vs the machine

Gold1390

Algorithms

Depth First Search

Dive deep along each branch before backtracking, using a stack or recursion.

4 min read · core · beat Gold to climb

Depth First Search

Depth first search, or DFS, explores a graph by going as deep as possible along one branch before backing up to try another. It is the workhorse behind cycle detection, connectivity checks, and topological ordering.

Stack or recursion

DFS naturally uses a stack, often the call stack through recursion. From the current node, pick an unvisited neighbor, descend into it, and repeat. When a node has no unvisited neighbors, backtrack to the previous node and continue.

Marking nodes visited prevents revisiting and protects against infinite loops in graphs with cycles.

What it reveals

The order in which DFS enters and leaves nodes carries information. Recording finish times supports topological sort, while detecting a node still on the current path reveals a cycle. DFS also identifies connected components by launching a fresh search from each unvisited node.

Like BFS, DFS touches every node and edge once, so its cost scales with the graph size.

Key idea

DFS plunges down one path until stuck, then backtracks, making it the basis for cycles, components, and ordering.

Check yourself

Answer to earn rating on the learn ladder.

1. Which structure underlies DFS, often implicitly?

2. What does DFS do when a node has no unvisited neighbors?