A Depth-First Search
14 — Algorithms
Dive deep — backtrack — detect cycles

Depth-First Search

Follow one path as far as it goes, then back up and try another. A stack — or plain recursion — does the bookkeeping, and back edges reveal cycles.

Depth-first search is breadth-first's mirror image. Instead of spreading out in rings, it commits to a single path and follows it as deep as possible before backing up. The engine is a stack — usually the call stack of recursion: visit a vertex, dive into its first unvisited neighbor, and only when you hit a dead end do you pop back and try another branch. Each vertex passes through three states — undiscovered, on the stack, and finished — and spotting an edge back to a vertex still on the stack instantly reveals a cycle. Like BFS, it touches every vertex and edge once: O(V + E).

Try it in 3D

Vertices are numbered in discovery order and colored by state: yellow on the stack, green finished. The strip below is the live stack — watch it grow on a dive and shrink on a backtrack.

Drag to rotate — scroll to zoom
stack ?empty
speed
Press —Run DFS— to watch it dive deep.ready
Current vertex On the stack Finished Tree edge Back edge / cycle

Why it works

A stack instead of a queue is the only change from BFS — and it flips the whole behavior from wide to deep.

Cost cheat sheet

Linear in the graph, with the recursion stack as the main memory cost.