Depth-first search follows one path as far as it can before backing up. You pick a start, mark it visited, then move to an unvisited neighbor and repeat. When a vertex has no unvisited neighbors left, you backtrack to the previous one and try its other branches.
You can drive this with recursion, which uses the call stack, or with an explicit stack.
function dfs(v, seen) {
seen.add(v);
for (const n of neighbors(v))
if (!seen.has(n)) dfs(n, seen); // recurse deeper
}
The visited set stops you from looping forever on cycles. DFS visits each vertex once and scans each edge once, so it runs in O(V + E) time, the same as BFS.
That depth-first order makes DFS natural for whole-graph questions, such as detecting cycles, finding connected components and producing a topological order. It suits problems about the graph's overall structure rather than the nearest distance.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓