Depth-first search

Explore a graph by going as deep as possible along each path before backtracking: the basis of cycle detection, topological sort and maze solving.

Description

Depth-first search follows one path as far as it can go, then backtracks to the most recent vertex with unexplored neighbors and tries the next one. Where breadth-first search spreads out in rings, DFS dives.

It's naturally written with recursion: visit a vertex, then recursively visit each unvisited neighbor. The call stack remembers where to return to. The same thing can be done with an explicit stack, which avoids running out of call stack on deep graphs, as in the step-through below.

DFS doesn't find shortest paths, but the order in which it starts and finishes vertices reveals structure. It's used to detect cycles (an edge back to a vertex still on the current path), produce a topological order (vertices in reverse finishing order), find connected components, solve mazes and puzzles, and as the skeleton of backtracking search.

How it works

ABCDEF

The graph we'll search, starting from A

  1. A — B
  2. A — C
  3. B — D
  4. C — D
  5. C — E
  6. D — F
  7. E — F
The graph we'll search, starting from A

Step through: iterative DFS from A. Numbers show discovery order.

ABCDEF

Stack (top last) AVisited in order none yet

Step 1 of 17Start at A: push it on the stack.

0 edges checked

Complexity

OperationAverageWorst
Traverse from one start vertexO(V + E)O(V + E)
Detect a cycleO(V + E)O(V + E)
With an adjacency matrixO(V²)O(V²)

Space: O(V) for the visited set and the stack (or recursion depth)

DFS typically uses less memory than BFS on wide graphs, because it only stores the current path and its pending neighbors.

TypeScript implementation

Recursive DFS, and cycle detection in a directed graph using three vertex colors.

depth-first-search.ts
// Depth-first search: a recursive traversal, and cycle detection in a
// directed graph using white (unvisited), gray (on the current path) and
// black (finished) colors.

type Graph = Record<string, string[]>;

export function dfsOrder(g: Graph, start: string): string[] {
  const visited = new Set<string>();
  const order: string[] = [];
  const visit = (v: string) => {
    visited.add(v);
    order.push(v);
    for (const n of g[v] ?? []) if (!visited.has(n)) visit(n);
  };
  visit(start);
  return order;
}

/** Returns a cycle as a list of vertices, or null if the directed graph has none. */
export function findCycle(g: Graph): string[] | null {
  const color = new Map<string, "gray" | "black">();
  const path: string[] = [];
  const visit = (v: string): string[] | null => {
    color.set(v, "gray");
    path.push(v);
    for (const n of g[v] ?? []) {
      if (color.get(n) === "gray") return [...path.slice(path.indexOf(n)), n]; // back edge
      if (!color.has(n)) {
        const c = visit(n);
        if (c) return c;
      }
    }
    path.pop();
    color.set(v, "black");
    return null;
  };
  for (const v of Object.keys(g)) if (!color.has(v)) {
    const c = visit(v);
    if (c) return c;
  }
  return null;
}

export function demo(): string[] {
  const g: Graph = { A: ["B", "C"], B: ["A", "D"], C: ["A", "D", "E"], D: ["B", "C", "F"], E: ["C", "F"], F: ["D", "E"] };
  const deps: Graph = { app: ["api"], api: ["db", "auth"], auth: ["db"], db: [] };
  const cyclic: Graph = { ...deps, db: ["app"] };
  return [
    `DFS order from A: ${dfsOrder(g, "A").join(" → ")}`,
    `cycle in dependencies: ${findCycle(deps)?.join(" → ") ?? "none"}`,
    `after db depends on app: ${findCycle(cyclic)?.join(" → ")}`,
  ];
}

When to use it

Use it when

  • You need to explore all paths or reach every vertex, and the order doesn't need to be by distance.
  • Cycle detection, topological sorting, connected and strongly connected components.
  • Backtracking puzzles: mazes, Sudoku, permutations.

Avoid it when

  • You need the shortest path in an unweighted graph: use BFS.
  • The graph is extremely deep and you're using recursion: switch to an explicit stack.
  • Edges have weights and you need the cheapest path: use Dijkstra.

Pitfalls

  • Stack overflow from deep recursion on long paths.
  • Confusing visited with on-path when detecting cycles in directed graphs: a vertex can be visited without being on the current path.
  • Non-deterministic order when neighbors come from an unordered set, which makes results hard to test.

Alternatives

Breadth-first search

Choose it when you need shortest paths by number of steps, or level-by-level processing.

Topological sort

Choose it when you need an order that respects dependencies (Kahn's algorithm avoids recursion).

Backtracking

Choose it when you're searching a space of choices rather than a fixed graph.