Skip to content
SimpleScope

Graphs

Breadth-first search vs Dijkstra's algorithm

Breadth-first search and Dijkstra's algorithm both explore a graph, in different ways. Breadth-first search: explore level by level with a queue. Dijkstra's algorithm: greedy: settle the closest unfinished node first (a simple list as the queue). In the worst case breadth-first search takes O(V + E) while Dijkstra's algorithm takes O(V²), so breadth-first search scales better on large inputs.

At a glance

PropertyBreadth-first searchDijkstra's algorithm
TechniqueExplore level by level with a queueGreedy: settle the closest unfinished node first (a simple list as the queue)
Best case timeO(V + E)O(V²)
Average case timeO(V + E)O(V²)
Worst case timeO(V + E)O(V²)
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 Dijkstra's algorithm when

edges have non-negative weights and you need the cheapest route.

Avoid it when

weights can be negative.

See them run

More comparisons