Data Structures & Algorithms / Module 8: Graphs

Topic 8.3

DFS

Go as deep as possible, back up at dead ends: for cycles, connectivity and ordering.

9 min · intermediate

Watch: the search goes as far as it can down one path, then backs up to the last fork at a dead end.

stackBADCFE
  • moving now
  • passed / marked
  • finished / the result
Step 1 of 13

DFS: go as deep as possible, and only back up at a dead end. Like exploring a maze with one hand on the wall.

DFS follows one path to a dead end, then backs up to the last fork it hasn't tried.

Like exploring a cave

In a cave with many tunnels, you go into the first tunnel and keep walking. At every fork, pick one and carry on. At a dead end, go back to the last fork and try a tunnel you haven't entered. The rope you've laid out from the entrance is the stack: it records the way back.

Code, for programmersRecursive DFS
function dfs(graph, start) {
  const seen = new Set();
  const order = [];
  (function visit(v) {
    seen.add(v);
    order.push(v);
    for (const u of graph.get(v) ?? []) {
      if (!seen.has(u)) visit(u);   // go deeper before trying the next neighbour
    }
  })(start);
  return order;
}

BFS or DFS

BFSDFS
Toolqueuestack (or recursion)
Shortest route (unweighted)YesNo
MemoryAs wide as a layerAs deep as the longest path
Good fordistances, 'nearest'cycles, connectivity, dependency order

Both visit every node and edge once: O(V + E).

Detecting a cycle

In a directed graph, give nodes three colours: not visited, on the current path (still on the stack), and finished. If DFS finds an edge to a node that is on the current path, you've looped back to yourself: there's a cycle. That's how bundlers report circular imports, and database migration tools reject circular dependencies.

Quiz

  1. What does DFS do at a dead end?

  2. You need the route with the fewest moves through a maze. Choose…

  3. In a DFS of a directed graph, an edge to a node still 'on the current path' means…

0 of 3 answered.