Professional Documents
Culture Documents
Dijkstra's Shortest Path Algorithm
Dijkstra's Shortest Path Algorithm
Dijkstra's Shortest Path Algorithm
• The problem:
– Given a weighted digraph and a vertex s in the
graph: find a shortest path from s to t
1 8
s A B t d(s,t)=6
-3
d(s, s4)=15 2
10
s
3 4 s2
Note: The shortest path 5
1
from s to s2 includes s1 as s1
Solution = {(s, 0), (s1, 5), (s2, 6),(s3, 8), (s4, 15) }
12/08/21 Cutler/Head Shortest Path 11
Implementing the selection rule
s4
Solution = {(s, 0)}
D[s1]=5 D[s2]= 15 8
s3
D[s1]=5 D[s3]=10 2
D[s1]=5 D[s4]=15 10
Node s1 is selected s
3 4 s2
Solution = {(s, 0), (s1, 5) } 5
1
s1
D[near ] = 5
Solution 2
after adding 3 2
near
s D[ v ] = 9
3 6 is updated to
D[v]=5+2=7
CS333 /Class 25 Shortest Path 13
Solution = {(s, 0)} Updating D Example
D[s1]=5, D[s2]= , D[s3]=10, D[s4]=15.
s4
Solution = {(s, 0), (s1, 5) }
D[s2]= D[s1]+w(s1, s2)=5+1=6, 15 8
s3
D[s3]= D[s1]+w(s1, s3)=5+4=9, 2
D[s4]=15 10
s
3 4 s2
Solution = {(s, 0), (s1, 5), (s2, 6) } 5
D[s3]=D[s2]+w(s2, s3)=6+2=8, 1
s1
D[s4]=15
Solution = {(s, 0), (s1, 5), (s2, 6), (s3, 8), (s4, 15) }
5. while PQ
(5) Loop = O (V ) - Only decreases
6. do near PQ.extractMin () (6+(5)) O (V ) O( lg V )
7. for each v Adj(near )
8 if D [ v ] > D [ near ] + w( near ,v ) (7+(5)) Loop = O(deg(near) ) = O( E )
9. then D [ v ] (8+(7+(5))) O(1)O( E )
D[near] + w(near,v) (9) O(1)
10. PQ.decreasePriorityValue (10+(7+(5))) Decrease- Key operation
on the heap can be implemented
(D[v ], v ) in O( lg V) O( E ).
11. return the label D[u] of each vertex u
a 4
4
2
b c
2
1
10
d 5 e
d 5 (c, d) 6(c, e)
e 6(c, e)