AlgoFrames

Depth-first search

Depth-first search follows one path as deep as it can, then backtracks. Watch the path dive and retreat alongside the call stack.

Before you start: Breadth-first search, Recursion: base case, recursive case, the call stack, Pre-order, in-order, post-order.

The idea

To explore a maze, walk down one corridor until it dead-ends. Then back up to the last fork and try the next corridor.

Depth-first search does exactly this on a graph. It dives as deep as it can and backs up only when it must.

Intuition

Start at 0 and keep moving to unvisited neighbors. The call stack holds the path: 0, 1, 3.

From 3 the search reaches 2. All neighbors of 2 are visited, so 2 is a dead end.

Backtrack to 3. It still has an unvisited neighbor, 4, so the search dives again.

Backing up is just a function returning. The caller resumes its loop where it stopped.

Complexity

Each node is visited once and each edge is checked from both ends. The work is O(V + E).

Marking nodes visited stops the search from entering any node twice. Without it, cycles would repeat forever.

Space is the call stack. On a long path it holds one frame per node, so O(V).

Pitfalls

Forget the visited check and the cycle 0, 1, 2 sends the search around forever. Crossed-out 2 calls 0 again.

A very deep graph can also overflow the call stack. An explicit stack avoids that.

Variations

Iterative DFS keeps its own stack of nodes to visit. Push neighbors in reverse so the first one is popped first.

A back edge leads to a node still on the stack. In this directed graph, 3→1 proves the cycle 1, 2, 3.

Code

Pseudocode

dfs(u):
  visited[u] ← true
  for each neighbor v of u
    if v not visited
      dfs(v)
dfs(source)

Python

def dfs(adj, u, visited, order):
    visited[u] = True
    order.append(u)
    for v in adj[u]:
        if not visited[v]:
            dfs(adj, v, visited, order)

JavaScript

function dfs(adj, u, visited, order) {
  visited[u] = true;
  order.push(u);
  for (const v of adj[u]) {
    if (!visited[v]) dfs(adj, v, visited, order);
  }
}

Cost at a glance

TimeO(V + E)
SpaceO(V)
InputAny graph
OutputVisit order and a DFS tree

Practice problems (6)

DFS order Warm-up

Depth-first search starts at node 0 and tries neighbors in the order the edges are listed. Drag the nodes into the order DFS visits them.

Back edge Warm-up

This directed graph is searched by DFS from node 0. A back edge points from a node to an ancestor still on the call stack. Click every back edge.

Recursive and iterative DFS Standard

Return the nodes in the order depth-first search visits them from source. Try neighbors in the order buildAdjacency(graph) lists them (edge-list order, both directions for undirected edges). Write it recursively, then again with an explicit stack.

In Python, build the adjacency lists from graph["edges"] yourself.

Is there a path? Standard

Return true when target can be reached from source by following edges, and false otherwise. A node reaches itself. For directed graphs follow edges only in their direction.

Cycle reachable from a node Standard

Given a directed graph, return true when a cycle can be reached from source. A cycle exists exactly when DFS finds a back edge: an edge to a node that is still on the call stack.

All paths from source to target Challenge

Given a directed acyclic graph, return every path from source to target. Each path lists its nodes in order. The paths may come back in any order.

Related topics

Next on the path: Connected components and flood fill