Professional Documents
Culture Documents
Introduction To Algorithms: Shortest Paths
Introduction To Algorithms: Shortest Paths
Shortest Paths
CSE 680
Prof. Roger Crawfis
Shortest Path
http://www.hp.com/
Shortest Path
2 23 3
9
s
18
Cost of path s-2-3-5-t
14
2 6 = 9 + 23 + 2 + 16
6 = 48.
30 4 19
11
15 5
5
6
20 16
7 t
44
Discussion Items
How many possible paths are there from s to t?
Can we safely ignore cycles? If so, how?
Any suggestions on how to reduce the set of possibilities?
Can we determine a lower bound on the complexity like we did
for comparison sorting?
2 23 3
9
s
18
14 6
2
6
30 4 19
11
15 5
5
6
20 16
7 t
44
Key Observation
A key observation is that if the shortest path contains
the node v, then:
It will only contain v once, as any cycles will only add to
the length.
The path from s to v must be the shortest path to v from s.
3
C 2 E
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: {}
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 }
Example of Dijkstra’s algorithm
Relax all edges leaving A: 10 ¥
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 }
Example of Dijkstra’s algorithm
“C” EXTRACT-MIN(Q): 10 ¥
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 }
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 }
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 }
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 }
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 }
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
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
Summary
• Given a weighted directed graph, we can
find the shortest distance between two
vertices by:
– starting with a trivial path containing the initial
vertex
– growing this path by always going to the next
vertex which has the shortest current path
Practice
t - -
f t 4 A
f t 2 A
f t 5 A
f t ∞10 9 - B F
f t ∞8 - B
Sincerely,
Douglas Wilhelm Harder, MMath
dwharder@alumni.uwaterloo.ca