DFS
Depth-first search walks a graph by going as deep as possible along one path before backtracking. You implement it with recursion or an explicit stack.
Detailed Explanation
DFS picks a neighbour, explores that whole branch, then tries the next neighbour. The order is not by distance from the start. The first time you reach a node is a path, not necessarily a shortest path.
The recursive form is short: mark visited, recurse on unmarked neighbours. The call stack is the path. That is useful and dangerous. Useful: you can detect a cycle in a directed graph with three colours (unseen / on the stack / done). Dangerous: a chain of 20,000 nodes overflows the JavaScript call stack. The iterative form uses an array as a stack (push/pop) and the heap instead of the call stack.
Time is O(n + m) on an adjacency list if you visit each node once. If you forget visited, a cycle never ends. On a tree you can skip visited if you never walk to the parent; on a general graph you cannot.
Preorder / inorder / postorder are DFS on binary trees with the visit placed before, between, or after the child calls. Connected components: start a DFS from every unseen node and group what you reach. Topological sort: add a node to a list after its descendants (postorder) on a DAG; a cycle makes that invalid.
Backtracking is DFS that undoes a choice (pop the path, unmark a cell) so the next sibling can try it. Maze search and N-queens are backtracking; they are still DFS.
What it costs you: stack overflows on deep graphs, and using DFS when you needed shortest edges (that is BFS). Recursion that mutates a shared path array must pop in a finally or after the recursive call, or later branches see leftover nodes.
Reach for DFS for existence, cycles, topological order, connected components, and search trees. Reach for BFS for unweighted shortest paths and level order. Reach for an explicit stack when depth is unbounded.
Code Examples
function dfs(adj, start) {
const visited = new Set();
const order = [];
function walk(node) {
if (visited.has(node)) return;
visited.add(node);
order.push(node);
for (const next of adj.get(node) ?? []) walk(next);
}
walk(start);
return order;
}
const adj = new Map([
["A", ["B", "C"]],
["B", ["D"]],
["C", []],
["D", []],
]);
console.log(dfs(adj, "A")); // => [ 'A', 'B', 'D', 'C' ]function hasDirectedCycle(adj) {
const state = new Map(); // 0 unseen, 1 stack, 2 done
function walk(node) {
const s = state.get(node) ?? 0;
if (s === 1) return true;
if (s === 2) return false;
state.set(node, 1);
for (const next of adj.get(node) ?? []) {
if (walk(next)) return true;
}
state.set(node, 2);
return false;
}
for (const node of adj.keys()) {
if ((state.get(node) ?? 0) === 0 && walk(node)) return true;
}
return false;
}
console.log(hasDirectedCycle(adj)); // => falsefunction dfsIter(adj, start) {
const visited = new Set();
const stack = [start];
const order = [];
while (stack.length) {
const node = stack.pop();
if (visited.has(node)) continue;
visited.add(node);
order.push(node);
const nexts = adj.get(node) ?? [];
for (let i = nexts.length - 1; i >= 0; i -= 1) stack.push(nexts[i]);
}
return order;
}
console.log(dfsIter(adj, "A")); // => [ 'A', 'B', 'D', 'C' ]Common Gotchas
Missing `visited` on a cyclic graph never returns
mark before you recurse.
Recursion depth follows the longest path
use an explicit stack for tall graphs.
DFS distance is not shortest
do not use first-reach depth as an unweighted shortest path.
Push neighbours in reverse if you want the same order as recursion
`pop` takes the last pushed child.