Depth-first search
Depth-first search keeps a stack instead of a queue. It takes the most recently added node, looks at its neighbours, and pushes the unseen ones on top — so the next node it examines is one it has only just discovered. The effect is that it walks as far as it can along one route, and only when that route is exhausted does it back up to the most recent junction it has not finished with.
Its frontier
A stack, taken from the top.
When it is the right choice
It is the natural choice when you need to visit everything rather than to find something close: enumerating every path, detecting cycles, finding strongly connected components, topological ordering by finish time, or exploring a tree. Its memory is bounded by the length of the current path rather than by the width of the graph, which is the opposite trade-off from breadth-first search. What it does not give you is a shortest path — the distances it records are the lengths of the routes it happened to take.
How it works
- Put the starting node on the stack.
- Take the node from the top of the stack.
- If it has already been visited, discard it and take the next.
- Otherwise mark it visited and push each unvisited neighbour on top.
- The neighbour pushed last is the one examined next, which is what makes this go deep.
- Stop when the stack is empty, or earlier once the target has been taken from it.
Worth noticing
- Compare the distance labels with breadth-first search’s on the same maze. They are mostly larger here, and that is not a bug: the number recorded is the length of the route this search took, and this search does not look for short ones.
- A node can sit in the stack more than once. It is discarded on the second arrival, and the pushed counter climbing faster than the settled counter is exactly that happening.
- The stack stays roughly as deep as the current path is long, where the queue in breadth-first search holds a whole level. On a wide, shallow graph that is a large difference in memory and the peak-frontier counter shows it.
Cost
- Best
- O(V + E)
- Average
- O(V + E)
- Worst
- O(V + E)
- Extra space
- O(V)
- Runs on
- a grid with walls; a weighted undirected graph; a directed acyclic graph; a directed graph with a cycle
- Largest grid
- 11 by 7 cells
- Largest graph
- 14 nodes, 28 edges
The limits are pedagogical rather than technical: this tool keeps a cost and a predecessor for every node in every recorded step, so the size of the graph sets the size of the trace directly, and a run has to stay short enough to sit and watch. A graph that would take more than three thousand steps on this algorithm is refused before a single step is generated, from a formula in the number of nodes and edges rather than by running it and finding out.
Graphs are generated from a seed, so the link in your address bar draws exactly the graph on your screen — no part of it is random in a way a reload could change.