A Shortest Path Algorithm
Motivation
Given a connected, positive weighted graph
Find the length of a shortest path from vertex a to vertex z.
Dijkstra’s Shortest Path Algorithm
Input: A connected, positive weighted graph,vertices a and z
Output: L(z), the length of a shortest path from a to z
1. Dijkstra(w,a,z,L){
2.
L(a)=0
3.
for all vertices x ≠a
4.
L(x)=∞
5.
T=set of all vertices
6.
while(z є T){
7.
choose v є T with minimum L(v)
8.
T=T-{v}
9.
for each x є T adjacent to v
10.
L(x)=min{L(x),L(v)+w(v,x)}
11.
}
12. }
Example 8.4.2
b
2
a
2
Find L(z)
4
3
3
5
1
e
7
f
c
4
d
1
2
g
z
6
Initialization
∞
b
2
0
a
2 ∞
d
1
∞
2
4
4
3
f
∞
c
∞ 3
e
7
5
1
g
∞
z
6
∞
Iteration 1
2
∞
b
2
0
a
2 ∞
d
1
∞
2
4
4
3
f
∞
1
c
∞ 3
e
7
5
1
g
∞
z
6
∞
Iteration 2
∞
2
b
2
0
a
1
2 ∞
4
d
2
4
4
3
c
∞ 3
e
7
f
1
5
1
g
∞
6
z
6
∞
Iteration 3
4∞
2
b
2
0
a
2 4
d
1
2
4
4
3
c
6∞ 3
e
7
f
1
5
1
g
6
z
6
∞
Iteration 4
2
b
2
0
a
2 4
d
1
4
2
4
4
3
c
6 6
e
7
f
1
5
1
g
6
z
6
5∞
Proof of Dijkstra’s Algorithm
Basic Step(i=1):
we set L(a)=0, and L(a) is sure the length of a shortest path from a to a.
Inductive step: For an arbitrary step i
Suppose for step k<i, L(v) is the length of a shortest path from a to v.
Next, suppose that at the it step we choose v in T with minimum L(v). We will seek a
contradiction that if there is a w whose length is less than L(v) then w is not in T.
By way of contradiction, suppose there is a w with L(w)<L(v), wєT. Then, let P be the
shortest path from a to w, and let x be the vertex nearest to a on P that is in T and let u be
x’s predecessor. The node u must not be in T (because x was the nearest node to a that was
in T). By assumption, L(u) was the length of the shortest path from a to u.
Then, L(x) ≤ L(u)+w(u,x) ≤ length of P < L(v). This is a contradiction. So w is not in T.
According to our assumption, every path from a to v has length at least L(v).
a
…
u
P
x
…
w
Example 2
b
3
c
2
2
1
a
z
1
2
d
Find L(z)
1
e
Initialization
∞
b
∞
3
c
2
2
0
1
a
z
1
2
d
∞
1
e
∞
∞
Iteration 1
a,2
∞
b
∞
3
c
2
2
0
1
a
z
1
2
d
∞
a,1
1
e
∞
∞
Iteration 2
∞
a,2
b
3
c
2
2
0
1
a
z
1
2
d
a,1
1
e
∞
d,2
∞
Iteration 3
b,5
∞
a,2
b
3
c
2
2
0
1
a
z
1
2
d
a,1
1
e
d,2
∞
Iteration 4
a,2
b
b,5
3
c
2
2
0
1
a
z
1
2
d
a,1
1
e
d,2
∞
e,4
Iteration 5
a,2
b
b,5
3
c
2
2
0
1
a
z
1
2
d
a,1
1
e
d,2
e,4
Theorem 8.4.5
For input consisting of an n-vertex, simple, connected, weighted
graph, Dijkstra’s algorithm has worst-case run time Ѳ(n2).
Proof: The while loop will take Ѳ(n2) worst-case running time.
© Copyright 2026 Paperzz