I am trying to find a shortest path between a source and a target using Floyd-Warshall's algorithm by computing the shortest paths between all pairs.
I need to find the shortest path not just the distance. This is what I'm trying to do:
I store the first vertex on the shortest path from i to j. Whenever the shortest path from i to j is updated and it now goes through k, I set the first vertex on the shortest path from i to j to that on the shortest path from i to k.
/*first[i][j] is the first vertex after i on the shortest path from i to j.
first[i][j] is initially j if there is an edge from i to j and the dist[i][j] is the weight of the edge. Otherwise f[i][j] is -1 and the cost is infinity.
*/
for(k = 0; k < N; ++k){
for(i = 0; i < N; ++i){
for(j = 0; j < N; ++j){
if(dist[i][j] >= dist[i][k]+dist[k][j]){
dist[i][j] = dist[i][k]+dist[k][j];
//When the distance is updated, update first[i][j]
first[i][j] = first[i][k];
}
}
}
}
The problem with this algorithm is that when I run this algorithm on the following graph, the path found by this algorithm is an infinite cycle.
Here is the first
matrix computed by the algorithm:
4 4 4 4 4 4
2 2 2 2 2 2
5 5 5 5 5 5
1 1 1 1 1 1
0 0 0 0 0 0
2 2 2 2 2 2
The first vertex on the shortest path from 0 to any other vertex, according to the algorithm is 4, but the first vertex on the shortest path from 4 to any other vertex is 0.
- Why does this algorithm behave in this manner ?
- Is there a another way to compute the first (after the source) vertex on every path while I am computing the length of the path?
I have read the Wikipedia article and also some questions on SO but they weren't of much help.