Graph Traversal

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

DFS on graph {A→B,C, B→D, D→E, C→E}step 1/5

// Array state

A
call
B
[1]
C
[2]
D
[3]
E
[4]
→ Graph: A→B,C. B→D. D→E. C→E. Start DFS at A. Push A onto call stack.

// Pseudocode

1// DFS — recursive
2function dfs(graph, node, visited):
3 visited.add(node)
4 process(node) // preorder
5 
6 for neighbor in graph[node]:
7 if neighbor not in visited:
8 dfs(graph, neighbor, visited)
9 
10 // postorder work here (e.g., topological sort push)

Key principles

1 / 4
1

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.

1 of 4

Recursive DFS

dfs-recursive.pseudo
1// DFS — recursive
2function dfs(graph, node, visited):
3 visited.add(node)
4 process(node) // preorder
5 
6 for neighbor in graph[node]:
7 if neighbor not in visited:
8 dfs(graph, neighbor, visited)
9 
10 // postorder work here (e.g., topological sort push)

Iterative DFS

dfs-iterative.pseudo
1// DFS — iterative (explicit stack)
2function dfsIter(graph, start):
3 stack = Stack([start])
4 visited = Set()
5 
6 while stack not empty:
7 node = stack.pop() // LIFO
8 if node in visited: continue
9 visited.add(node)
10 process(node)
11 
12 for neighbor in graph[node]:
13 if neighbor not in visited:
14 stack.push(neighbor)

Cycle detection

dfs-cycle.pseudo
1// Cycle detection — directed graph
2function hasCycle(graph):
3 visited = Set() // fully done
4 recStack = Set() // currently in DFS path
5 
6 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 // recurse
12 elif n in recStack:
13 return true // back edge = cycle!
14 recStack.remove(node)
15 return false

Complexity

Time — visits every vertex and edge onceO(V + E)

O(V + E) time

Space — call stack depth equals height h of DFS treeO(h)

O(h) time

Space worst case — on a path graph h = VO(V)

O(V) time

⚠️Recursive DFS can stack overflow
On graphs with millions of nodes, recursive DFS will exhaust the call stack. Use the iterative version (explicit stack) for production code on large graphs.
🔍DFS tree edges
During DFS you classify edges: tree edges (new nodes), back edges (ancestor — indicates cycle in directed graph), forward edges (descendant via different path), cross edges (different subtrees). Back edges are the key cycle indicator.

🎯 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.