Dijkstra's Algorithm: Slide Courtesy: Uwash, UT
Dijkstra's Algorithm: Slide Courtesy: Uwash, UT
1
Single-Source Shortest Path Problem
4 1 3 10
2 2 ∞
∞ C D E
5 8 ∞ 4 6
1
F G
∞ ∞
7
Example: Update neighbors'
distance
0 2
2
A B
4 1 3 10
2 2 ∞
∞ C D E
5 8 1 4 6
Distance(B) = 2 1
F G
Distance(D) = 1
∞ ∞
8
Example: Remove vertex with
minimum distance
0 2
2
A B
4 1 3 10
2 2 ∞
∞ C D E
5 8 1 4 6
1
F G
∞ ∞
9
Example: Update neighbors
0 2
2
A B
4 1 3 10
2 2
3 C D E 3
5 8 1 4 6
Distance(C) = 1 + 2 = 3 1
F G
Distance(E) = 1 + 2 = 3
Distance(F) = 1 + 8 = 9 9 5
Distance(G) = 1 + 4 = 5
10
Example: Continued...
Pick vertex List with minimum distance (E) and update neighbors
0 2
2
A B
4 1 3 10
2 2
3 C D E 3
5 8 1 4 6
1
F G
No updating
9 5
12
Example: Continued...
Pick vertex List with minimum distance (C) and update neighbors
0 2
2
A B
4 1 3 10
2 2
3 C D E 3
5 8 1 4 6
Distance(F) = 3 + 5 = 8 1
F G
8 5
13
Example (end)
0 2
2
A B
4 1 3 10
2 2
3 C D E 3
5 8 1 4 6
1
F G
Pick vertex not in S with lowest cost (F) and update neighbors
15
Another Example
Another Example
Another Example
Another Example
Another Example
Another Example
Another Example
Another Example
Another Example
Correctness :“Cloudy” Proof
When a vertex is added to the cloud, it has shortest
distance to source.
competitor v'
Source
• If the path to v is the next shortest path, the path to v' must be at
least as long. Therefore, any path through v' to v cannot be shorter!
Dijkstra Correctness (2)
27
Dijkstra Correctness (3)
d
[] d
u (s
,)
u (
in
it
ialas
sump
tio
n)
d
(s
,)
yd
(y
,)
u(opt
im a
lsub
st
ruc
tu
re)
d
[y
]d
(y
,)
u (cor
rect
nes
sofd[
y])
d
[y
] (
nonegat
ive
w e
ig
hts
)
28
Dijkstra’s Pseudo Code
• Graph G, weight function w, root s
relaxing
edges
29
Time Complexity: Using List
Time Complexity: Priority Queue
31