16 - Shortest Path Algorithms - Dijkstra
16 - Shortest Path Algorithms - Dijkstra
2
Relaxation
• For each vertex v in the graph, we maintain Dv,
the estimate of the shortest path from s
(initialized to ¥ at the start)
• Relaxing an edge (u,v) with cost duv means
testing whether we can improve the shortest
path to v found so far by going through u
u v u v
2 2 Relax (u,v,G)
5 9 5 6
if Dv > Du+duv then
Relax(u,v,G) Relax(u,v,G) Dv =
Du+duv
5 2 7 5 2 6
Parentv
u v u v
= u
3
Dijkstra's Algorithm
• Non-negative edge weights 4
s x
– Dijkstra’s doesn’t work with negative edges:
2 6
v y
-9
4
Dijkstra’s Pseudo Code
• Input: Graph G, start vertex s
Dijkstra(G(V,E),s)
01 for each vertex u Î V
02 Du ¬ ¥
03 Parentu ¬ nil
04 Ds ¬ 0
05 S ¬ Æ // Set S : already solved
vertices
06 Q.init(V) // Q, intially contains all nodes in G
07 while not Q.isEmpty()
08 u ¬ Q.extractMin() //chose unvisited u with min
Du relaxing
09 S ¬ S È {u}
10 for each v Î u.adjacent() do edges
11 Relax(u, v, G)
5
Dijkstra’s Example
Dijkstra(G(V,E),s) Pv= Æ
Pu = Æ
01 for each vertex u Î V u v
Du ¬ ¥
1
02 10 ¥ ¥
03 Parentu ¬ nil P s= Æ
9
04 Ds ¬ 0 s 0 2 3
4 6
05 S ¬ Æ 7
5
06 Q.init(V) ¥ 2 ¥
07 while not Q.isEmpty() Px= Æ x y Py= Æ
08 u ¬ Q.extractMin() //grey
09 S ¬ S È {u} //black
10 for each v Î u.adjacent() do u s v Æ
1
11 Relax(u, v, G) 10 10 ¥
Æ 9
2 3
Relax (u,v,G) s 0 4 6
if Dv > Du+duv then 5 7
Dv
5 2 ¥ Æ
s x y
= Du+duv
6
Dijkstra’s Example (2)
Dijkstra(G(V,E),s)
01 for each vertex u Î V u x v x
1
02 Du ¬ ¥ 10 8 14
03 Parentu ¬ nil Æ 9
04 Ds ¬ 0 s 0 2 3
4 6
05 S ¬ Æ 7
5
06 Q.init(V) 5 2 7 x
07 while not Q.isEmpty() x s y
08 u ¬ Q.extractMin() //grey
09 S ¬ S È {u} //black
10 for each v Î u.adjacent() do x u v y
1
11 Relax(u, v, G) 10 8 13
Æ 9
s 0 2 3
Relax (u,v,G) 4 6
7
if Dv > Du+duv then 5
Dv 5 2 7 x
s x y
= Du+duv
7
Dijkstra’s Example (3)
Dijkstra(G(V,E),s)
u x v u
01 for each vertex u Î V
1
02 Du ¬ ¥ 10 8 9
03 Parentu ¬ nil Æ 9
04 Ds ¬ 0 s 0 2 3
4 6
05 S ¬ Æ 7
5
06 Q.init(V) 5 2 7 x
07 while not Q.isEmpty()
x s y
08 u ¬ Q.extractMin() //grey
09 S ¬ S È {u} //black
10 for each v Î u.adjacent() do x u v u
1
11 Relax(u, v, G) 10 8 9
Æ 9
s 0 2 3
Relax (u,v,G) 4 6
7
if Dv > Du+duv then 5
Dv 5 2 7 x
s x y
= Du+duv
8
Dijkstra's Algorithm
• Dijkstra’s Complexity:
– O(|V| x |E|)