Professional Documents
Culture Documents
The problem: find the shortest path between every pair of vertices of a graph The graph: may contain negative edges but no negative cycles A representation: a weight matrix where W(i,j)=0 if i=j. W(i,j)=g if there is no edge between i and j. W(i,j)=weight of edge
1 v2 2 2 4 3 v3
Solution
Set each vertex as source and call Dijkstras algo But we may solve the problem using direct approach (Algorithm By Floyd)
Floyds Algo
Assume vertices are numbered as 1,2,3n for simplicity Uses nn matrix D (n is the number of vertices in the graph G) Shortest paths are computed in matrix D After running the algorithm D[i,j] contains the shortest distance (cost) between vertices i and j
Floyds Algo
Initially we set D[i,j]=W[i,j] Remember
We make n iteration over matrix D After kth iteration D[i,j] will store the value of minimum weight path from vertex i to vertex j that does not pass through a vertex numbered higher than k
Floyds Algo
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)
Vi
Vj
Shortest Path using intermediate vertices { V1, . . . Vk -1 }
Floyeds Algorithm
Floyd 1. D n W // initialize D array to W [ ] 2. 3. for k n 1 to n 4. do for i n 1 to n 5. do for j n 1 to n 6. if (D[ i, j ] > D[ i, k ] + D[ k, j ] ) then 7. D[ i, j ] n D[ i, k ] + D[ k, j ]
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
Recovering Paths
Floyd 1. D n W // initialize D array to W [ ] 2. P n 0 3. for k n 1 to n 4. do for i n 1 to n 5. do for j n 1 to n 6. if (D[ i, j ] > D[ i, k ] + D[ k, j ] ) then 7. D[ i, j ] n D[ i, k ] + D[ k, j ] 8. P [ i, j] n k
Example
W= 1 4 2 2 -3 P= 5 3 1 2 3 1 0 0 0 2 0 0 0 3 0 0 0 D0 = 1 2 3 1 0 2 w 2 4 0 -3 3 5 w 0
1
4
5 2 -3
D0 = 3
1 2 3
1 0 2 w 3 5 7 0 3 0 1 0
2 4 0 -3
3 5 w 0
1 1= D 2 3
1 0 2 w 1 0 0 0
2 4 0 -3 2 0 0 0
P=
1 2 3
1
4
5 2 -3
D1 = 1 3 2 3 2 4 0 -3 2 0 0 0
1 0 2 w 3 5 7 0 3 0 1 0
2 4 0 -3
3 5 7 0
1 2= D 2 3
1 0 2 -1 1 0 0 2
P=
1 2 3
1
4
5 2 -3
D2 = 1 1 0 3 2 3 2 2 0 -3 2 3 0 0 2 -1 3 5 7 0 3 0 1 0
2 4 0 -3
3 5 7 0
D3 =
1 2 3
1 0 2 -1 1 0 0 2
P=
1 2 3
1
4
5 2 -3