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.
Watch: the search goes as far as it can down one path, then backs up to the last fork at a dead end.
- moving now
- passed / marked
- finished / the result
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
| BFS | DFS | |
|---|---|---|
| Tool | queue | stack (or recursion) |
| Shortest route (unweighted) | Yes | No |
| Memory | As wide as a layer | As deep as the longest path |
| Good for | distances, '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
What does DFS do at a dead end?
You need the route with the fewest moves through a maze. Choose…
In a DFS of a directed graph, an edge to a node still 'on the current path' means…
0 of 3 answered.