Depth-first search
A stack, or recursion, and going as deep as possible first.
Before you start
Depth-first search picks a direction and commits. From the start node it walks to a neighbour, then to *that* node's neighbour, and keeps going as deep as the graph allows — only backing up when it hits a dead end.
That behaviour comes from using a **stack** instead of a queue. A stack is last-in-first-out, so the most recently discovered node is the next one explored, which pulls the search downward rather than outward.
Most of the time you don't write the stack yourself — **recursion gives you one for free**, because the call stack already works exactly this way. This lesson shows both forms and makes the frames visible as they pile up.
Graph
DFS follows one path to its end before backing upStack
one frame per open call — this is the stackOne frame open. A is visited; its neighbours are about to be tried.
Step 1 of 8. Start at A. `dfs(A)` is called. A is marked visited and recorded, and a frame for it appears on the call stack. That frame will sit there — paused mid-loop — for the entire time the search explores everything reachable below A.
Step 01 / 08
Start at A
dfs(A) is called. A is marked visited and recorded, and a frame for it appears on the call stack.
That frame will sit there — paused mid-loop — for the entire time the search explores everything reachable below A.
/* Recursive — the call stack IS the stack */void dfs(Graph *g, int node, bool visited[]) { visited[node] = true; visit(node); for (int nb : neighbours(g, node)) if (!visited[nb]) dfs(g, nb, visited); /* go deep first */}/* Iterative — an explicit stack, same traversal */void dfs_iter(Graph *g, int start) { bool visited[N] = { false }; Stack s; push(&s, start); while (!empty(&s)) { int node = pop(&s); /* LIFO: newest first */ if (visited[node]) continue; visited[node] = true; visit(node); for (int nb : neighbours(g, node)) if (!visited[nb]) push(&s, nb); }}