A navigation app must find the shortest route from where you are to everywhere else. In a weighted graph with non-negative weights, Dijkstra’s algorithm solves exactly this problem.
The problem and relaxation
The single-source shortest-path problem : given a weighted graph and a source vertex s s s , find the length of a shortest path from s s s to every vertex (and the paths themselves).
Every shortest-path algorithm in this unit keeps two arrays:
d[v]: the length of the shortest path to v v v found so far (an upper estimate, initially ∞, and d[s] = 0);
pi[v]: the predecessor of v v v on that path.
Definition 8.6 · Edge relaxation
Relaxing the edge ( u , v ) (u, v) ( u , v ) with weight w ( u , v ) w(u, v) w ( u , v ) means: if d [ u ] + w ( u , v ) < d [ v ] d[u] + w(u, v) < d[v] d [ u ] + w ( u , v ) < d [ v ] , set d [ v ] = d [ u ] + w ( u , v ) d[v] = d[u] + w(u, v) d [ v ] = d [ u ] + w ( u , v ) and π [ v ] = u \pi[v] = u π [ v ] = u . In words: if going through u u u gives a shorter way to v v v , use it.
Dijkstra’s algorithm
Intuition
Pour water into a network of pipes at the source. The water reaches the nearest junction first, then spreads on; a junction’s arrival time can never improve after the water has reached it. Dijkstra’s algorithm “settles” vertices in exactly this order of distance.
Set d[v] = ∞ and pi[v] = nil for all v v v ; set d[s] = 0; let S S S (settled vertices) be empty .
Repeat n n n times: pick the vertex u ∉ S u \notin S u ∈ / S with the smallest d[u] (Extract-Min); add u u u to S S S ; relax every edge ( u , v ) (u, v) ( u , v ) leaving u u u .
This is a greedy algorithm: at each step it commits to the closest unsettled vertex. It is correct only when all edge weights are non-negative : then no later path can come back to a settled vertex more cheaply.
Correction · What Dijkstra's algorithm computes, and its starting set
Study material says: §8.3.1 says “Dijkstra’s algorithm is a greedy algorithm, which finds shortest path between all pairs of vertices in the graph”, and its pseudocode initialises S := { 0 }.
Correct version: Dijkstra’s algorithm finds the shortest paths from one source to all vertices (single-source); all-pairs paths need it to be run once from every vertex, or the Floyd–Warshall algorithm. The set of settled vertices starts empty , S := ∅; the source is the first vertex extracted because d[s] = 0.
Why: The same section calls the problem “single-source shortest paths”, and the algorithm takes one source s s s . S := {0} would put a vertex into S S S before its edges were relaxed. Cormen et al., §24.3, initialise S = ∅ S = \emptyset S = ∅ .
Example 8.7 Dijkstra on the example graph of §8.3.1
Goal. Find shortest paths from s s s in the digraph with edges s→u 10, s→x 5, u→v 1, u→x 2, v→y 4, x→u 3, x→v 9, x→y 2, y→s 7, y→v 6.
Program. The O ( n 2 ) O(n^2) O ( n 2 ) array version: Extract-Min is a linear scan; the line after each step shows all current estimates.
C · dijkstra.c Copy #include <stdio.h>
#define N 5
#define INF 1000000 /* larger than any real path length */
const char * name = "suvxy" ; /* vertex 0 = s, 1 = u, 2 = v, 3 = x, 4 = y */
int main( void )
{
/* weighted digraph of the worked example in Section 8.3.1 (0 = no edge) */
int w[N][N] = { 0 };
w[ 0 ][ 1 ] = 10 ; w[ 0 ][ 3 ] = 5 ; /* s->u, s->x */
w[ 1 ][ 2 ] = 1 ; w[ 1 ][ 3 ] = 2 ; /* u->v, u->x */
w[ 2 ][ 4 ] = 4 ; /* v->y */
w[ 3 ][ 1 ] = 3 ; w[ 3 ][ 2 ] = 9 ; w[ 3 ][ 4 ] = 2 ; /* x->u, x->v, x->y */
w[ 4 ][ 0 ] = 7 ; w[ 4 ][ 2 ] = 6 ; /* y->s, y->v */
int d[N], pi[N], inS[N];
for ( int v = 0 ; v < N; v ++ ) { d[v] = INF; pi[v] = - 1 ; inS[v] = 0 ; }
d[ 0 ] = 0 ; /* source s */
for ( int round = 0 ; round < N; round ++ ) {
int u = - 1 ; /* Extract-Min: closest vertex not in S */
for ( int v = 0 ; v < N; v ++ )
if ( ! inS[v] && (u == - 1 || d[v] < d[u]))
u = v;
if (d[u] == INF) break ; /* the rest is unreachable */
inS[u] = 1 ;
for ( int v = 0 ; v < N; v ++ ) /* relax every edge (u, v) */
if (w[u][v] && ! inS[v] && d[u] + w[u][v] < d[v]) {
d[v] = d[u] + w[u][v];
pi[v] = u;
}
printf( "add %c to S: d =" , name[u]);
for ( int v = 0 ; v < N; v ++ ) {
if (d[v] == INF) printf( " %c=inf" , name[v]);
else printf( " %c=%d" , name[v], d[v]);
}
printf( " \n " );
}
printf( "shortest paths from s: \n " );
for ( int v = 1 ; v < N; v ++ ) {
char path[N + 1 ];
int len = 0 ;
for ( int x = v; x != - 1 ; x = pi[x]) path[len ++ ] = name[x];
printf( " %c: length %2d, path " , name[v], d[v]);
while (len > 0 ) printf( "%c" , path[ -- len]);
printf( " \n " );
}
return 0 ;
}
Run it.
Output Copy add s to S: d = s=0 u=10 v=inf x=5 y=inf
add x to S: d = s=0 u=8 v=14 x=5 y=7
add y to S: d = s=0 u=8 v=13 x=5 y=7
add u to S: d = s=0 u=8 v=9 x=5 y=7
add v to S: d = s=0 u=8 v=9 x=5 y=7
shortest paths from s:
u: length 8, path sxu
v: length 9, path sxuv
x: length 5, path sx
y: length 7, path sxy
Read the steps. s is settled first (u = 10, x = 5). x is closest: through x, u improves to 8, v to 14, y to 7. y is next (7): v improves to 13. u is next (8): v improves to 9. Finally v (9).
Result. Distances u = 8, v = 9, x = 5, y = 7, with paths s→x→u, s→x→u→v, s→x and s→x→y.
Running time
Implementation of Extract-Min Time Array or unsorted list (scan all vertices) O ( n 2 ) O(n^2) O ( n 2 ) , best for dense graphsBinary heap (priority queue, Unit 5) O ( ( n + e ) log n ) O((n + e) \log n) O (( n + e ) log n ) , best for sparse graphs
Dijkstra’s algorithm works for directed and undirected graphs, as long as no weight is negative.
Key idea
Dijkstra’s algorithm repeatedly settles the unsettled vertex with the smallest distance estimate and relaxes its outgoing edges; with non-negative weights this greedy choice gives correct single-source shortest paths in O ( n 2 ) O(n^2) O ( n 2 ) (array) or O ( ( n + e ) log n ) O((n + e)\log n) O (( n + e ) log n ) (heap).
TEE Exam note
“Apply Dijkstra’s algorithm to the graph, starting at vertex …” is a standard 8–10 mark question. Draw a table with one column per vertex and one row per step, showing d (and the predecessor) after each vertex is settled; circle the settled vertex in each row; finish with the paths. State the non-negative-weight condition and the complexity. Check Your Progress 2, Q1: the basis of Dijkstra’s algorithm is edge relaxation (with a greedy choice of the closest vertex).
Common mistake
Updating the distance of a vertex that is already settled. Once a vertex is in S S S , its distance is final.
Common mistake
Using Dijkstra’s algorithm on a graph with negative edges. It may settle a vertex too early and return wrong distances; use Bellman–Ford instead.
Key takeaways
Relax ( u , v ) (u, v) ( u , v ) : if d [ u ] + w < d [ v ] d[u] + w < d[v] d [ u ] + w < d [ v ] , update d [ v ] d[v] d [ v ] and π [ v ] \pi[v] π [ v ] .
Dijkstra: start with S = ∅ S = \emptyset S = ∅ , d [ s ] = 0 d[s] = 0 d [ s ] = 0 ; repeatedly settle the closest unsettled vertex and relax its edges.
Correct only for non-negative weights; works on directed and undirected graphs.
O ( n 2 ) O(n^2) O ( n 2 ) with an array; O ( ( n + e ) log n ) O((n + e) \log n) O (( n + e ) log n ) with a binary heap.
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice Which problem does Dijkstra’s algorithm solve directly?
A All-pairs shortest paths B Single-source shortest paths with non-negative weights C Minimum spanning tree D Shortest paths with negative cycles
Check answer
Show answer Answer: B. Single-source shortest paths with non-negative weights
It computes distances from one source. For all pairs it must be run n n n times (or use Floyd–Warshall).
Question 2 · multiple choice Current estimates are d[a] = 4, d[b] = 7, and edge a→b has weight 2. After relaxing a→b, what is d[b]?
A 7 B 2 C 6 D 11
Check answer
Show answer Answer: C. 6
4 + 2 = 6 < 7, so d[b] becomes 6 and π[b] = a. 11 would be adding 7 + 4.
Question 3 · multiple choice In the example, why does v’s distance change three times?
A Because v has a negative edge B Because v is settled three times C Because each newly settled vertex (x, y, u) offers a shorter way to v D Because the algorithm is wrong
Check answer
Show answer Answer: C. Because each newly settled vertex (x, y, u) offers a shorter way to v
14 via x, 13 via y, 9 via u. Estimates only decrease, and v is settled once, at 9.
Question 4 · multiple choice What is the running time of Dijkstra’s algorithm when Extract-Min scans an array of n n n vertices?
Check answer
Show answer Answer: D. O ( n 2 ) O(n^2) O ( n 2 )
n n n Extract-Min operations of O ( n ) O(n) O ( n ) each, plus O ( e ) ≤ O ( n 2 ) O(e) \le O(n^2) O ( e ) ≤ O ( n 2 ) relaxations.
Question 5 · multiple choice What does this program print?
C · q8-relax.c Copy #include <stdio.h>
int main( void )
{
int d[ 4 ] = { 0 , 1000 , 1000 , 1000 }; /* source 0, others "infinity" */
int w[ 4 ][ 4 ] = {{ 0 , 4 , 1 , 0 },
{ 0 , 0 , 0 , 1 },
{ 0 , 2 , 0 , 5 },
{ 0 , 0 , 0 , 0 }};
int done[ 4 ] = { 0 };
for ( int r = 0 ; r < 4 ; r ++ ) {
int u = - 1 ;
for ( int v = 0 ; v < 4 ; v ++ )
if ( ! done[v] && (u < 0 || d[v] < d[u])) u = v;
done[u] = 1 ;
for ( int v = 0 ; v < 4 ; v ++ )
if (w[u][v] && d[u] + w[u][v] < d[v]) d[v] = d[u] + w[u][v];
}
printf( "%d %d %d \n " , d[ 1 ], d[ 2 ], d[ 3 ]);
return 0 ;
} A 3 1 4 B 4 1 5 C 4 1 6 D 3 1 6
Check answer
Show answer Answer: A. 3 1 4
Settle 0 (d1 = 4, d2 = 1); settle 2 (d1 = 1 + 2 = 3, d3 = 6); settle 1 (d3 = 3 + 1 = 4); settle 3. “4 1 5” ignores the cheaper route 0→2→1.
Question 6 · short answer
Apply Dijkstra’s algorithm to Figure 8.5 (edges 1→2 3, 1→3 6, 1→5 9, 2→4 1, 3→4 8, 3→5 6, 4→5 6) from vertex 1, showing the distances after each step.
Show worked answer Start: d = (0, ∞, ∞, ∞, ∞). Settle 1: d2 = 3, d3 = 6, d5 = 9. Settle 2 (3): d4 = 3 + 1 = 4. Settle 4 (4): 4 + 6 = 10 > 9, d5 stays 9. Settle 3 (6): 3→4 gives 14 > 4; 3→5 gives 12 > 9. Settle 5 (9). Final: d(1..5) = 0, 3, 6, 4, 9; paths 1→2, 1→3, 1→2→4, 1→5.