Code Snippets
/

DFS Traversal Template

DFS Traversal Template

Depth-first search visits a node, then recursively visits each unvisited neighbor before backtracking. It is the natural traversal for tree problems, cycle detection, topological order, and connected-components. This snippet covers the recursive form, an iterative stack-based form for very deep graphs, and a path-tracking variant that surfaces the actual route from start to a target.

JavaScript
Medium
3 snippets
algorithms
dfs
code-template
stack

180 views

5

function dfs(start, getNeighbors) {
    const visited = new Set();
    const order = [];
    function visit(node) {
        if (visited.has(node)) return;
        visited.add(node);
        order.push(node);
        for (const next of getNeighbors(node)) visit(next);
    }
    visit(start);
    return order;
}

const graph = { A: ['B', 'C'], B: ['D'], C: ['D', 'E'], D: [], E: [] };
console.log(dfs('A', (n) => graph[n])); // [A, B, D, C, E]

Recursive DFS uses the call stack as the implicit traversal stack. The visited set prevents cycles from causing infinite recursion, and pushing onto the order list at visit-time produces a pre-order traversal. The recursion depth is the length of the longest path from start, which matters for very deep graphs (V8's default stack supports ~10000 frames). For small to moderate graphs this is the cleanest implementation; for huge ones see the iterative form in the next accordion.