← Back

Depth-First Search

graphrecursivebacktracking
Press play to start
1function dfs(graph: Record<string, string[]>, start: string): string[] {
2 const visited = new Set<string>();
3 const stack = [start];
4 const order: string[] = [];
5 while (stack.length > 0) {
6 const node = stack.pop()!;
7 if (visited.has(node)) continue;
8 visited.add(node);
9 order.push(node);
10 for (const nb of (graph[node] ?? []).slice().reverse()) {
11 if (!visited.has(nb)) stack.push(nb);
12 }
13 }
14 return order;
15}
Step 1/0

Complexity

Best:O(V+E)
Average:O(V+E)
Worst:O(V+E)
Space:O(V)

Description

Explores as far as possible along each branch before backtracking. Uses a stack (or recursion) to track nodes to visit.

When to use

Cycle detection, topological sort, path finding, maze solving. Memory-efficient for deep graphs compared to BFS.