Depth-First
Search
Dive as deep as possible along one path before backtracking. DFS powers cycle detection, topological sort, connected components, and maze solving — all with just O(V) space from the call stack.
How does depth-first search (DFS) work?
DFS explores as far as possible along one path before backtracking. It's implemented with recursion, or an explicit stack, plus a visited set, and runs in O(V + E). DFS is the tool for detecting cycles, topological sorting, finding connected components, solving mazes and backtracking problems like permutations.
function dfs(graph, node, visited = new Set()) {
if (visited.has(node)) return visited;
visited.add(node);
for (const next of graph[node] ?? []) dfs(graph, next, visited);
return visited;
}
// count islands in a grid
function islands(grid) {
let count = 0;
const sink = (r, c) => {
if (grid[r]?.[c] !== 1) return;
grid[r][c] = 0;
sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
};
grid.forEach((row, r) => row.forEach((v, c) => { if (v === 1) { count++; sink(r, c); } }));
return count;
}Deep-dive traversal — animated
// Array state
// Pseudocode
Key principles
Stack-based — LIFO dive
DFS uses a stack (implicit call stack in recursion, or explicit in iterative version). It always follows one path as deep as possible before backtracking. LIFO is the opposite of BFS's FIFO.
Recursive DFS
1// DFS — recursive2function dfs(graph, node, visited):3 visited.add(node)4 process(node) // preorder56 for neighbor in graph[node]:7 if neighbor not in visited:8 dfs(graph, neighbor, visited)910 // postorder work here (e.g., topological sort push)
Iterative DFS
1// DFS — iterative (explicit stack)2function dfsIter(graph, start):3 stack = Stack([start])4 visited = Set()56 while stack not empty:7 node = stack.pop() // LIFO8 if node in visited: continue9 visited.add(node)10 process(node)1112 for neighbor in graph[node]:13 if neighbor not in visited:14 stack.push(neighbor)
Cycle detection
1// Cycle detection — directed graph2function hasCycle(graph):3 visited = Set() // fully done4 recStack = Set() // currently in DFS path56 function dfs(node):7 visited.add(node)8 recStack.add(node)9 for n in graph[node]:10 if n not in visited:11 if dfs(n): return true // recurse12 elif n in recStack:13 return true // back edge = cycle!14 recStack.remove(node)15 return false
Complexity
O(V + E) time
O(h) time
O(V) time
🎯 Quick Check
Which DFS traversal order is used for topological sort?
Depth-First Search: summary
Key points
- Deep recursion can overflow the call stack on large graphs; switch to an explicit stack.
- DFS doesn't find shortest paths.
- Pre-order and post-order on graphs mirror the tree traversals.
Frequently asked questions
›When should I use DFS?
When you need to explore every path or region (cycle detection, connected components, mazes, backtracking), and the shortest path doesn't matter.