13 ShortestPath
13 ShortestPath
Shortest Path
Dr. Lê Nguyên Khôi
The VNU University of Engineering and Technology
Contents
Path definition
Shortest path properties
Single-source shortest path
All-pairs shortest path
Example:
Optimal substructure
A sub-path of a shortest path is the
shortest path
is the shortest path
from to
is the sub-path of
from to với
is the shortest path from to
Triangle inequality
For all vertices , we have
Negative weight
If a graph contains a negative-weight cycle,
then some shortest paths may not exist
Greedy strategy:
1. Maintain a set of vertices whose shortest-
path distances from are known
2. At each step add to the vertex
whose distance estimate from is minimal
3. Update the distance estimates of vertices
adjacent to
Initialization
0
2 9
3 5 2
1 4 1
1 4
8
Add to
0
2 9
3 5 2
1 4 1
1 4
8
Add to
0
2 9
3 5 2
1 4 1
1 4
8
Add to
0
2 9
3 5 2
1 4 1
1 4
8
Add to
0
2 9
3 5 2
1 4 1
1 4
8
for each do
while do times
for each do
if then
Complexity Analysis:
Design and Analysis of Algorithms 20
Breadth First Search
5 1 0 5 ∞ ∞
50 30 15
5
2 50 0 15 5
3 30 ∞ 0 15
15
2 3 4 15 ∞ 5 0
15 2 50 0 15 5
1 4 3 30 ∞ 0 15
5 4 15 ∞ 5 0
5 15
5 50 30
1 2 3 4
1 0 5 ∞ ∞
15
2 3 2 50 0 15 5
3 30 35 0 15
4 15 20 5 0
15 2 50 0 15 5
1 4 3 30 35 0 15
5 4 15 20 5 0
5 15
5 50 30
1 2 3 4
1 0 5 20 10
15
2 3 2 50 0 15 5
3 30 35 0 15
4 15 20 5 0
15 2 50 0 15 5
1 4 3 30 35 0 15
5 4 15 20 5 0
5 15
5 50 30
1 2 3 4
1 0 5 20 10
15
2 3 2 45 0 15 5
3 30 35 0 15
4 15 20 5 0
15 2 45 0 15 5
1 4 3 30 35 0 15
5 4 15 20 5 0
5 15
5 50 30
1 2 3 4
1 0 5 15 10
15
2 3 2 20 0 10 5
3 30 35 0 15
4 15 20 5 0
Thus,
Initialization
for to do
for to do
for to do
if then
Run in time
Simple to code
Efficient in practice
Design and Analysis of Algorithms 30