AlgoScope

Breadth-First Search vs Depth-First Search

Graph TraversalAlgorithmbeginner

Breadth-First Search and Depth-First Search are both graph traversal. Play them side by side below, then see exactly where they diverge.

Either player can stop before each decision and ask what happens next: turn on Predict mode in its top bar.

Breadth-First Search

Full topic

Explore layer by layer with a queue. Discovers shortest paths in unweighted graphs.

Breadth-first search from vertex 0 with a queue.0012345
Breadth-first search from 0. A queue holds the frontier. Take the vertex that has waited longest, look at its neighbours, and enqueue the ones never seen before with their distance. Because of the queue, vertices come out in order of distance from the start.

DEQUEUE -> VISIT -> ENQUEUE unvisited neighbours. The frontier expands in rings. Queue drawn alongside.

Depth-First Search

Full topic

Go as deep as possible before backtracking. The recursion stack is the frontier.

Depth-first search from vertex 0 with a stack.012345
Depth-first search from 0 with an explicit stack. Pop the top, and if it is new, visit it and push its unvisited neighbours. The stack makes the search dive: the vertex pushed last is explored first, before its siblings.

DESCEND along an edge -> dead end -> BACKTRACK. The call stack grows and shrinks beside the graph.

How they differ

Both visit everything reachable from the start in O(V + E). What differs is which vertex they take next. Breadth-first search takes the oldest from a queue, so it spreads out layer by layer and reaches each vertex by the fewest edges, which is why it finds shortest paths in an unweighted graph. Depth-first search takes the newest, from the recursion stack, so it follows one path as deep as it goes before backtracking.

The run shown here takes 8 steps for Breadth-First Search and 10 steps for Depth-First Search (Depth-first from 0). That count moves with the input - use the example tabs above either player to see it change.

What each operation costs, for Breadth-First Search and Depth-First Search side by side.
CostBreadth-First SearchDepth-First Search
bestO(V + E)O(V + E)
averageO(V + E)O(V + E)
worstO(V + E)O(V + E)
spaceO(V)O(V)