Dijkstra
Dijkstra
L14.2
Shortest paths
A shortest path from u to v is a path of
minimum weight from u to v. The shortest-
path weight from u to v is defined as
d(u, v) = min{w(p) : p is a path from u to v}.
L14.3
Well-definedness of shortest
paths
If a graph G contains a negative-weight cycle,
then some shortest paths may not exist.
Example: …
<0
u v
L14.6
Single-source shortest paths
Problem. From a given source vertex s V, find
the shortest-path weights d(s, v) for all v V.
If all edge weights w(u, v) are nonnegative, all
shortest-path weights must exist.
IDEA: Greedy.
1. Maintain a set S of vertices whose shortest-
path distances from s are known.
2. At each step add to S the vertex v V – S
whose distance estimate from s is minimal.
3. Update the distance estimates of vertices
adjacent to v.
L14.7
Dijkstra’s algorithm
d[s] 0
for each v V – {s}
do d[v]
S
QV ⊳ Q is a priority queue maintaining V – S
while Q
do u EXTRACT-MIN(Q)
S S {u}
for each v Adj[u]
do if d[v] > d[u] + w(u, v) relaxation
then d[v] d[u] + w(u, v) step
Implicit DECREASE-KEY
L14.8
Example of Dijkstra’s
algorithm
Graph with 2
B D
nonnegative 10
edge weights: 8
A 1 4 7 9
3
C 2 E
L14.9
Example of Dijkstra’s
algorithm
Initialize: 2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0
S: {}
L14.10
Example of Dijkstra’s
algorithm
“A” EXTRACT-MIN(Q): 2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0
S: { A }
L14.11
Example of Dijkstra’s
algorithm
10
Relax all edges leaving A: 2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0 3
10 3
S: { A }
L14.12
Example of Dijkstra’s
algorithm
10
“C” EXTRACT-MIN(Q): 2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0 3
10 3
S: { A, C }
L14.13
Example of Dijkstra’s
algorithm
Relax all edges leaving C: 7 11
2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0 3 5
10 3
7 11 5
S: { A, C }
L14.14
Example of Dijkstra’s
algorithm
“E” EXTRACT-MIN(Q): 7 11
2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0 3 5
10 3
7 11 5
S: { A, C, E }
L14.15
Example of Dijkstra’s
algorithm
Relax all edges leaving E: 7 11
2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0 3 5
10 3
7 11 5
7 11 S: { A, C, E }
L14.16
Example of Dijkstra’s
algorithm
“B” EXTRACT-MIN(Q): 7 11
2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0 3 5
10 3
7 11 5
7 11 S: { A, C, E, B }
L14.17
Example of Dijkstra’s
algorithm
Relax all edges leaving B: 7 9
2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0 3 5
10 3
7 11 5
7 11 S: { A, C, E, B }
9
L14.18
Example of Dijkstra’s
algorithm
“D” EXTRACT-MIN(Q): 7 9
2
B D
10
8
0 A 1 4 7 9
3
Q: A B C D E C 2 E
0 3 5
10 3
7 11 5
7 11 S: { A, C, E, B, D }
9
L14.19
Analysis of Dijkstra
while Q
do u EXTRACT-MIN(Q)
|V | S S {u}
times for each v Adj[u]
degree(u) do if d[v] > d[u] + w(u, v)
times then d[v] d[u] + w(u, v)