Beruflich Dokumente
Kultur Dokumente
1
Recall the All-Pairs Shortest Paths Problem
a 20 b a −20 b
6 e 3 e
12 8 4 4 5
5 3 4
4
17 10
d c d c
2
Solutions Covered in the Previous Lecture
time .
time .
plexity .
It also illustrate that there could be more than one way
of developing a dynamic programming algorithm.
3
Solution 3: the Input and Output Format
./
Output Format: an distance - 10 where
/ $
is the distance from vertex # to .
4
Step 1: The Floyd-Warshall Decomposition
6575858
Definition: The vertices 243 2 2 9<;>= are called the
:
@ 585857
6
intermediate vertices of the path ? 2 = 2:3 2A9CB .
/ED)FHG
Let be the length of the shortest path from
$
# to such that any intermediate vertices on the
KLM565M56N%O
path (if any) are chosen from the set I'J .
/ DQP:G
is defined to be , i.e., no intermediate ver-
tex.
DQFHG .R/%D)FHG
Let - be the matrix 0 .
/EDTSG $
is the distance from # to . So our aim is to
DUSG
compute - .
DQFHG N 6VMV6VMWX5
Subproblems: compute - for J
"
Observation 1:
A shortest path does not contain the same vertex twice.
Proof: A path that contains the same vertex twice,
contains a cycle. Removing the cycle gives a shorter
path.
$
Observation 2: For a shortest path from # to such
that any intermediate vertices on the path are chosen
WKLM56565MN%O
from the set I'J , there are two possibilities:
N
1. is not a vertex on the path,
/YDQF ;>= G
The shortest such path has length .
N
2. is a vertex on the path.
/YDQF ;>= G /ED)F ;>= G
The shortest such path has length F Z F .
6
Step 2: Structure of shortest paths
$
Consider a shortest path from # to containing the
N N
vertex . It consists of a subpath from # to and a
N $
subpath from to .
Each of them only contains intermediate vertices in
M585858 N [ O
IJ J , and must be as short as possible,
/ D)F ;>= G / D)F ;>= G
namely F and F .
/ QD F ;>= G / QD F ;>= G
Hence the path has length F Z F .
7
Step 3: the Bottom-up Computation
DQP:G .
Bottom: - aM0 , the weight matrix.
8
The Floyd-Warshall Algorithm
f
Floyd-Warshall( )
g
for # J to do
$
for J to do
g /h. ) $ . &$
# 0 # 0;
/h. &$
?EiAj # 0 )# k ;
l
N
for J to do
for # J to do
$
for J to do
d/h. mN /h.nNop$ /h. ) $
if # 0 Z 0q # 0
g /h. & $ h / . N /h.nNop$
# 0 # 0 Z 0;
/h. p$ N
?EiAj # 0 ;
l
/h. 575rX 585s
return J J 0;
l
9
Comments on the Floyd-Warshall Algorithm
.{z|d}
The predecessor pointer tvuxwAy 0 can be used
to extract the final path (see next page).
10
Extracting the Shortest Paths
.z`d}
The predecessor pointers tvu~wAy 0 can be used to
extract the final path. The idea is as follows.
$ /h. )$
To find the shortest path from # to , we consult ?%iAj # 0 .
)$'
11
The Algorithm for Extracting the Shortest Paths
Q$
Path( # )
g /h. &$
if (?EiAj # 0 #)k ) single edge
&$'
output # ;
else compute the two parts of the path
g
/h. p$
Path( # ?EiAj # 0 );
/h. p$ ) $
Path(?%ij # 0 );
l
l
12
Example of Extracting the Shortest Paths
13