DFS commits to one branch and follows it as deep as possible before backtracking to try the next. Swap BFS's queue for a stack (or plain recursion, the call stack IS a stack) and you get depth-first behavior. The first time you reach any node, you've found SOME path to it, but by exploring one rabbit hole completely before neighbors, there's no reason that path is short.
DFS is the natural choice for structural questions rather than distance questions: does a cycle exist (did we touch a node currently "in progress"?), how many connected components are there (count DFS launches from unvisited nodes), can we reach B from A at all, topological ordering of a DAG, and generating/exhausting possibilities (backtracking in Module 7 is DFS over decision space).
Both forms
// Recursive, the call stack does the bookkeeping
function dfs(adj, node, visited = new Set()) {
visited.add(node);
// process node here (pre-order)
for (const nb of adj[node]) {
if (!visited.has(nb)) dfs(adj, nb, visited);
}
}
// Iterative, explicit stack, same visit order semantics
function dfsIterative(adj, start) {
const visited = new Set();
const stack = [start];
const order = [];
while (stack.length) {
const node = stack.pop(); // LIFO, deepest first
if (visited.has(node)) continue; // may be pushed twice; skip lazily
visited.add(node);
order.push(node);
for (const nb of [...adj[node]].reverse()) { // reversed → smallest popped first
if (!visited.has(nb)) stack.push(nb);
}
}
return order;
}
// Cycle detection, three colors: unvisited / in-progress / done
function hasCycle(adj) {
const state = new Array(adj.length).fill(0); // 0 new, 1 in stack, 2 done
function visit(v) {
state[v] = 1;
for (const nb of adj[v]) {
if (state[nb] === 1) return true; // back edge → cycle!
if (state[nb] === 0 && visit(nb)) return true;
}
state[v] = 2;
return false;
}
for (let v = 0; v < adj.length; v++) if (state[v] === 0 && visit(v)) return true;
return false;
}| Operation / case | Cost | Notes |
|---|---|---|
| Time (adjacency list) | O(V + E) | same as BFS, each node/edge once |
| Space (recursive) | O(V) | worst case: recursion depth = path length |
| Space (iterative) | O(V) | explicit stack |
| Shortest path? | No | finds SOME path, use BFS for shortest |