Skip to content
SimpleScope

Graphs

Breadth-first search vs Depth-first search

Breadth-first search and Depth-first search both explore a graph, in different ways. Breadth-first search: explore level by level with a queue. Depth-first search: go as deep as possible first, with recursion or a stack. In the worst case both take O(V + E), so the choice comes down to the other differences below.

At a glance

PropertyBreadth-first searchDepth-first search
TechniqueExplore level by level with a queueGo as deep as possible first, with recursion or a stack
Best case timeO(V + E)O(V + E)
Average case timeO(V + E)O(V + E)
Worst case timeO(V + E)O(V + E)
Extra spaceO(V)O(V)
Stable (equal values keep their order)Not applicableNot applicable
In place (no extra array)Not applicableNot applicable
Needs sorted inputNoNo

When to choose each

Choose breadth-first search when

you need the fewest edges between two nodes, or the nodes level by level.

Avoid it when

the edges have different weights.

Choose depth-first search when

you need to explore every path, find connected groups or detect cycles.

Avoid it when

you need the shortest path.

See them run

More comparisons