Skip to main content
Intermediate ~15 min read

Depth-First Search

Dive deep, backtrack, repeat, the stack-driven traversal behind cycle detection, component counting, and maze exploration.

Prerequisites: Graph Representations, Recursion Basics

DFS commits to one branch and follows it as deep as possible before backtracking to try the next. Swap BFS's queue for a stack (or plain recursion, the call stack IS a stack) and you get depth-first behavior. The first time you reach any node, you've found SOME path to it, but by exploring one rabbit hole completely before neighbors, there's no reason that path is short.

DFS is the natural choice for structural questions rather than distance questions: does a cycle exist (did we touch a node currently "in progress"?), how many connected components are there (count DFS launches from unvisited nodes), can we reach B from A at all, topological ordering of a DAG, and generating/exhausting possibilities (backtracking in Module 7 is DFS over decision space).

Both forms

dfs.js
// Recursive, the call stack does the bookkeeping
function dfs(adj, node, visited = new Set()) {
  visited.add(node);
  // process node here (pre-order)
  for (const nb of adj[node]) {
    if (!visited.has(nb)) dfs(adj, nb, visited);
  }
}

// Iterative, explicit stack, same visit order semantics
function dfsIterative(adj, start) {
  const visited = new Set();
  const stack = [start];
  const order = [];
  while (stack.length) {
    const node = stack.pop();          // LIFO, deepest first
    if (visited.has(node)) continue;   // may be pushed twice; skip lazily
    visited.add(node);
    order.push(node);
    for (const nb of [...adj[node]].reverse()) {  // reversed → smallest popped first
      if (!visited.has(nb)) stack.push(nb);
    }
  }
  return order;
}

// Cycle detection, three colors: unvisited / in-progress / done
function hasCycle(adj) {
  const state = new Array(adj.length).fill(0);   // 0 new, 1 in stack, 2 done
  function visit(v) {
    state[v] = 1;
    for (const nb of adj[v]) {
      if (state[nb] === 1) return true;          // back edge → cycle!
      if (state[nb] === 0 && visit(nb)) return true;
    }
    state[v] = 2;
    return false;
  }
  for (let v = 0; v < adj.length; v++) if (state[v] === 0 && visit(v)) return true;
  return false;
}
Operation / caseCostNotes
Time (adjacency list)O(V + E)same as BFS, each node/edge once
Space (recursive)O(V)worst case: recursion depth = path length
Space (iterative)O(V)explicit stack
Shortest path?Nofinds SOME path, use BFS for shortest

Check your understanding

  1. 1.The ONLY data-structure change that turns BFS into DFS is:
  2. 2.Counting connected components: run DFS from every UNVISITED node, incrementing a counter per launch. Why does this work?
  3. 3.In a maze, DFS finds an exit but the path is absurdly long. Best explanation?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

BFS & DFS Maze Explorer

Play, pause, and scrub the real algorithm step by step.

Play it

Maze Runner

Race your own path through a maze, then watch BFS find the provably shortest route, and DFS show why 'a path' …

Keep going