Search

Search papers and lessons

Dijkstra's Algorithm

Level 2 · 11 min read

Dijkstra's algorithm finds the shortest route from one start point to every other point in a graph with non-negative edge lengths, by always settling the nearest unsettled point next.

On this page

  • Colour = topic mix
  • Algorithms
  • Discrete math
  • Calculus
  • ReadReady to readNot yet

TL;DR

Dijkstra's algorithm finds the shortest route from one starting vertex to every other vertex in a Graph whose edges all have non-negative lengths. It keeps a tentative distance for each vertex, always settles the unsettled vertex with the smallest tentative distance, and then tries to shorten the routes that leave it. Once a vertex is settled its distance is final.

Builds on: Graph, Priority Queue, Greedy Algorithm · Leads to: Breadth-First Search (the same idea with equal lengths)

Where it's used

  • Driving directions. A navigation system models roads as a Graph, with intersections as vertices and travel times as edge lengths. Dijkstra-style searches, often sped up with extra tricks, find the fastest route from where you are to where you want to go.
  • Network routing. Link-state routing protocols let each router compute shortest paths over the network topology. Each router runs a shortest-path computation from itself to every other router, and the result decides where packets are forwarded.
  • Planning moves in a grid. A robot or game character on a map with costs for rough ground can treat each cell as a vertex and find the cheapest path. Cells with higher cost get larger edge lengths, and all lengths stay non-negative.

How it works

Take a small directed graph. The start is S and the goal is T. The numbers on the edges are lengths.

  • S to A: 4
  • S to B: 1
  • B to A: 2
  • A to C: 1
  • B to C: 6
  • C to T: 3

Keep a tentative distance d for each vertex. Start with d(S) = 0 and every other distance set to infinity. Keep a set of settled vertices, which starts empty. The step that makes the algorithm work is called relaxing an edge: if going from a settled vertex u to a neighbour v gives a shorter route than d(v), replace d(v) with the new, shorter value.

  1. Start at S. d(S) = 0, and every other distance is infinity. Check: the only distance we know for sure is zero at the start.
  2. Settle S and relax its edges. S has the smallest distance, 0, so settle it. Going to A costs 0 + 4 = 4, which beats infinity, so d(A) = 4. Going to B costs 0 + 1 = 1, so d(B) = 1. Check: each tentative value is the length of a real route.
  3. Settle the nearest unsettled vertex, B at distance 1. Relax B's edges. Going to A costs 1 + 2 = 3, which beats 4, so d(A) = 3. Going to C costs 1 + 6 = 7, so d(C) = 7. Check: A's route is now S to B to A, which is shorter than S to A directly.
  4. Settle A at distance 3. Relax A's edge to C. Going to C costs 3 + 1 = 4, which beats 7, so d(C) = 4. Check: C's route is now S to B to A to C.
  5. Settle C at distance 4. Relax C's edge to T. Going to T costs 4 + 3 = 7, so d(T) = 7.
  6. Settle T at distance 7. T is the goal, so the answer is 7. Its route is S to B to A to C to T, with lengths 1 + 2 + 1 + 3 = 7. The direct route S to A to C to T would cost 4 + 1 + 3 = 8.

The final distances are S 0, B 1, A 3, C 4, T 7. The step that made the algorithm fast was the choice at each step: picking the smallest tentative distance is safe, because no unvisited route can later undercut it when every edge length is non-negative.

flowchart TD
  A["Set d(start) = 0, all others infinity"] --> B{"Any unsettled vertices left?"}
  B -- no --> E["Done: d holds shortest distances"]
  B -- yes --> C["Settle the unsettled vertex u with smallest d(u)"]
  C --> D["For each edge u to v: if d(u) + length < d(v), set d(v) to it"]
  D --> B

The math

Let G have vertices V and edges E, where each edge (u, v) has a length w(u,v)≥0w(u, v) \ge 0. Let SS be the set of settled vertices, and let d(v)d(v) be the current tentative distance to v.

Step 1 in symbols

Start with the source ss and set

d(s)=0,d(v)=∞ for every other v∈V,S=∅d(s) = 0, \qquad d(v) = \infty \text{ for every other } v \in V, \qquad S = \varnothing

In the example, d(S)=0d(S) = 0 and every other entry is infinity.

Step 2 in symbols

Relaxing an edge from u to v means

if d(u)+w(u,v)<d(v), then set d(v)=d(u)+w(u,v)\text{if } d(u) + w(u, v) < d(v), \text{ then set } d(v) = d(u) + w(u, v)

In the example, relaxing B to A gives d(B)+w(B,A)=1+2=3d(B) + w(B, A) = 1 + 2 = 3, and 3<43 < 4, so d(A)d(A) becomes 3.

Step 3 in symbols

At each round, pick the unsettled vertex u with the smallest d(u)d(u), add it to S, and relax its outgoing edges. The reason this is correct is a Greedy Algorithm argument, a cut argument: suppose some route to u were shorter than d(u)d(u). That route must leave the settled set at some edge (x, y) with x∈Sx \in S and y not settled. Then d(y)≤d(x)+w(x,y)≤d(y) \le d(x) + w(x, y) \le the length of the route to u, since the route is at least as long as its prefix, because all edges are non-negative. But d(y)≥d(u)d(y) \ge d(u), because u was chosen as the smallest. So the shorter route cannot exist, and d(u)d(u) is final.

Using a Priority Queue such as a binary heap, each vertex is removed once and each edge is relaxed at most once. The total cost is

O((∣V∣+∣E∣)log⁡∣V∣)O\big((|V| + |E|) \log |V|\big)

in the Big-O Notation sense, where the Logarithm comes from heap operations.

Worked examples

Example
1. Two routes to T (tiny)

Edges: S to A of length 2, A to T of length 2, and S to T of length 5. Find the shortest route from S to T.

  1. Start: d(S) = 0. Settle S. Relax: d(A) = 2, d(T) = 5.
  2. Settle A at 2. Relax A to T: 2 + 2 = 4, which beats 5, so d(T) = 4.
  3. Settle T at 4. It is the goal.
  4. The answer is 4, along S, A, T.

Interpretation: the direct edge costs 5, while the two-edge detour through A costs 4, so the detour is the better route.

Example
2. The six-edge graph from the walkthrough (standard)

Use the graph from How it works. Find the distance from S to every vertex.

  1. Settle S at 0. d(A) = 4, d(B) = 1.
  2. Settle B at 1. Relax B to A: 1 + 2 = 3, so d(A) = 3. Relax B to C: 1 + 6 = 7, so d(C) = 7.
  3. Settle A at 3. Relax A to C: 3 + 1 = 4, so d(C) = 4.
  4. Settle C at 4. Relax C to T: 4 + 3 = 7, so d(T) = 7.
  5. Settle T at 7.
  6. Final distances: S 0, B 1, A 3, C 4, T 7.

Interpretation: every vertex gets one final number, and each number comes from a route that the algorithm has checked. The walkthrough showed why the detour through B wins.

Example
3. A warehouse delivery network (realistic)

A warehouse W sends vans along roads measured in minutes. Roads: W to P 7, W to Q 3, Q to P 2, Q to R 6, P to R 4, R to X 2, and P to X 9. Find the fastest time from W to the customer X.

  1. Start: d(W) = 0. Settle W. Relax: d(P) = 7, d(Q) = 3.
  2. Settle Q at 3. Relax Q to P: 3 + 2 = 5, which beats 7, so d(P) = 5. Relax Q to R: 3 + 6 = 9, so d(R) = 9.
  3. Settle P at 5. Relax P to R: 5 + 4 = 9, which does not beat 9, so d(R) stays 9. Relax P to X: 5 + 9 = 14, so d(X) = 14.
  4. Settle R at 9. Relax R to X: 9 + 2 = 11, which beats 14, so d(X) = 11.
  5. Settle X at 11. It is the customer.
  6. The fastest time is 11 minutes, along W, Q, R, X. The other two routes cost 14 (W, Q, P, X) and 13 (W, P, R, X).

Try it: a new road from Q directly to X of 5 minutes is opened. What is the new fastest time from W to X? Answer: 8 minutes. Step 2 now also relaxes Q to X: 3 + 5 = 8, which beats 14 and 11, so d(X) = 8. The route is W, Q, X. Every other step still applies, and no unsettled vertex can give a shorter time than 8.

Common mistakes and tradeoffs

Mistake: the algorithm works with any edge lengths. It is tempting to think that Dijkstra's algorithm handles negative lengths too. In fact it can give wrong answers with them, because it settles a vertex once and never reopens it. Take S to A of length 2, S to B of length 3, and B to A of length -2. The algorithm settles A at 2, but the route S, B, A has length 3 - 2 = 1. Edges must be non-negative for the settled values to be final.

Mistake: the algorithm needs the full table to find one answer. It is tempting to think that finding the distance to one target requires computing everything. In fact the algorithm can stop as soon as the target is settled, because its distance is then final. The other distances are not needed for that single answer.

When to use it. Use it when all edge lengths are non-negative and you need shortest distances from one source. With a heap it is fast on large sparse graphs, such as road networks.

When not to use it. Use a method that accepts negative edges, such as the Bellman-Ford method, when lengths can be negative. Use a breadth-first search instead when every edge has the same length, since it is simpler and just as correct. For a dense graph, a simple array search for the smallest distance can be faster than a heap.

History

Edsger Dijkstra designed the algorithm in the mid-1950s and published it in 1959 in a short paper on problems involving graphs. It was first presented as a way to find the shortest path between two cities, and it was one of the early examples of a greedy method that is proved optimal. It caught on because it is simple to state, and because later work on heaps and graph data structures made it practical for large networks.

Recap

  • Dijkstra's algorithm keeps a tentative distance for each vertex and settles the nearest unsettled vertex at each step.
  • Relaxing an edge replaces a tentative distance with a shorter route through a settled vertex.
  • The non-negative edge rule is what makes a settled distance final.
  • With a priority queue, the cost is O((∣V∣+∣E∣)log⁡∣V∣)O((|V| + |E|) \log |V|).
  • Read next: Breadth-First Search for the special case where every edge has the same length, and Greedy Algorithm for the idea that makes the settle step safe.

Check yourself

QuestionIn one sentence, what does it mean to relax an edge?Show answer

Relaxing an edge from u to v checks whether going through u gives a shorter route to v than the current tentative distance. If it does, the tentative distance of v is replaced with the shorter value.

QuestionEdges: S to A of length 1, A to B of length 4, S to B of length 6, B to T of length 1, and A to T of length 7. Find the shortest distance from S to T.Show answer

Settle S at 0, giving d(A) = 1 and d(B) = 6. Settle A at 1, relaxing A to B: 1 + 4 = 5, which beats 6, so d(B) = 5. A to T gives 8. Settle B at 5, relaxing B to T: 5 + 1 = 6, which beats 8, so d(T) = 6. Settle T at 6. The answer is 6, along S, A, B, T.

QuestionWhy does a wrong answer appear when one edge has a negative length, even though the algorithm always settles the smallest tentative distance?Show answer

A negative edge can make a route through a still-unsettled vertex end up cheaper than a settled vertex's distance. The algorithm never reconsiders a settled vertex, so it misses that cheaper route. The non-negative edge rule is what guarantees that no later route can undercut a settled distance.

QuestionA courier app must find the fastest time from a depot to one house on a road network with no negative travel times. Should it run the full algorithm to every vertex?Show answer

No. Dijkstra's algorithm can stop as soon as the house is settled, because its distance is final at that point. The rest of the network does not need to be finished. Stopping early saves time on large maps.

Sources