0

In the Floyd-Warshall algorithm, the shortest path cost is computed for any pair of vertices. Additional book-keeping allows us to keep the actual path (list of vertices) on the shortest path.

How can I extend Floyd-Warshall so that for any pair of vertices, the top-K shortest paths are found? For example, for K=3, the result would be that the 3 shortest paths are computed and maintained?

I have been using the Java implementation from Sedgewick.

stackoverflowuser2010
  • 38,621
  • 48
  • 169
  • 217

2 Answers2

2

Sounds more like Dijkstra would be simpler to modify for returning N shortest paths. The search is allowed to enter the vertex until K shortest alternatives has entered the vertex.

For more information you can check wikipedia article

Pauli Nieminen
  • 1,100
  • 8
  • 7
  • Not sure if it is a requirement (question did not specify), but Dijkstra's algorithm can not handle negative edge weights. – RishiG Sep 11 '14 at 18:30
0

You may call the loop multiple times using an extra condition that could like

for (int i = 0; i < V; i++) { // compute shortest paths using only 0, 1, ..., i as intermediate vertices for (int v = 0; v < V; v++) { if (edgeTo[v][i] == null) continue; // optimization for (int w = 0; w < V; w++) { if (distTo[v][w] > distTo[v][i] + distTo[i][w] && distTo[v][i]+distTo[i][w]>min[k]) { //min[k] is the minimum distance calculated in kth iteration of minimum distance calculation distTo[v][w] = distTo[v][i] + distTo[i][w]; edgeTo[v][w] = edgeTo[i][w]; } } // check for negative cycle if (distTo[v][v] < 0.0) { hasNegativeCycle = true; return; } } } This code will calculate the K minimum distances that are different. Hope it would help you.

Zeshan Khan
  • 294
  • 2
  • 15