JavaScript Snippet

DFS Traversal Template

Difficulty: Medium

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.

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

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.