Skip to content
SimpleScope

Graphs

Depth-first search vs Dijkstra's algorithm

Depth-first search and Dijkstra's algorithm both explore a graph, in different ways. Depth-first search: go as deep as possible first, with recursion or a stack. Dijkstra's algorithm: greedy: settle the closest unfinished node first (a simple list as the queue). In the worst case depth-first search takes O(V + E) while Dijkstra's algorithm takes O(V²), so depth-first search scales better on large inputs.

At a glance

PropertyDepth-first searchDijkstra's algorithm
TechniqueGo as deep as possible first, with recursion or a stackGreedy: 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 depth-first search when

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

Avoid it when

you need the shortest path.

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