Академический Документы
Профессиональный Документы
Культура Документы
Data Structures
Data Structures
Data Structures
v1
3
5
v5
3
v2
v4
2
4
3
v3
Data Structures
Solution
Dijkstras Algorithm can be used.
How?
Data Structures
Floyds Algo
Data Structures
Floyds Algo
Initially we set D[i,j]=W[i,j]
Remember
W[i,j]=0 if i==j
W(i,j)= if there is no edge between i and j
W(i,j)=weight of edge
Data Structures
Floyds Algo
In kth iteration we use following formula to compute D
Dk 1[i, j ]
Dk [i, j ] min
Dk 1[i, k ] Dk 1[k , j ]
Subscript k denotes the value of matrix D after the kth iteration (It
should not be assumed there are n different matrices of size nn)
Data Structures
Floyeds Algorithm
Floyd
1. D W // initialize D array to W [ ]
2.
3. for k 1 to n
4.
do for i 1 to n
5.
do for j 1 to n
6.
if (D[ i, j ] > D[ i, k ] + D[ k, j ] ) then
7.
D[ i, j ] D[ i, k ] + D[ k, j ]
Data Structures
Recovering Paths
Use another matrix P
P[i,j] hold the vertex k that led Floyd to find the smallest value of
D[i,j]
If P[i,j]=0 there is no intermediate edge involved, shortest path
is direct edge between i and j
So modified version of Floyd is given
Data Structures
Recovering Paths
Floyd
1. D W // initialize D array to W [ ]
2. P 0
3. for k 1 to n
4.
do for i 1 to n
5.
do for j 1 to n
6.
if (D[ i, j ] > D[ i, k ] + D[ k, j ] ) then
7.
D[ i, j ] D[ i, k ] + D[ k, j ]
8.
P [ i, j] k
Data Structures
Example
W=
1
4
5
2
D0 =
1
0
2
4
3
5
2
3
0
-3
1
2
1
0
0
2
0
0
3
0
0
3
-3
P=
1
4
D0 =
5
2
-3
1
0
2
1
2
3
1
1
D =
2
1
0
2
2
4
0
3
5
7
-3
P=
1
2
3
1
0
0
0
2
0
0
0
3
0
1
0
2
4
0
-3
Data Structures
3
5
k=1
Vertex 1 can be intermediate
node
1
4
D1 =
5
2
-3
1
2
3
1
0
2
1
2
D =
2
1
0
2
2
4
0
3
5
7
-1
-3
1
2
3
1
0
0
2
2
0
0
0
3
0
1
0
P=
2
4
0
-3
Data Structures
3
5
7
0
k=2
Vertices 1, 2 can be
intermediate
1
4
D3 =
P=
D2 = 1
5
1 0
3
2
2 2
-3
3 -1
2
4
0
-3
1
2
1
0
2
2
2
0
3
5
7
-1
-3
1
2
3
1
0
0
2
2
3
0
0
3
0
1
0
3
5
7
0
Data Structures
k=3
Vertices 1, 2, 3 can be
intermediate
Data Structures
1
P= 2
3
1
4
1
0
0
2
2
3
0
0
5
2
-3
3
0
1
0