0

Here is my code to implement Floyd algorithm. How can I change this algorithm to solve this question: Find the minimum distances between vertices i and j with at most S vertices between them.

void Floyd_Warshal(int graph[MAX][MAX], int D[MAX][MAX], int P[MAX][MAX], int numberOfNodes){
    for(int i = 0 ; i < numberOfNodes ; i++)
        for(int j = 0 ; j < numberOfNodes ; j++){
            D[i][j] = graph[i][j];
            P[i][j] = -1;
        }
    for(int k = 0 ; k < numberOfNodes ; k++)
        for(int i = 0 ; i < numberOfNodes ; i++)
            for(int j = 0 ; j < numberOfNodes ; j++)
                if(D[i][j] > D[i][k] + D[k][j]){
                    D[i][j] = D[i][k] + D[k][j];
                    P[i][j] = k;
                }
}

1 Answers1

1

Bellman-Ford algorithm (the slightly modified version that does not use found paths from current iteration) on every iteration i can find all shortest paths that use at most i edges. Floyd-Warshall algorithm is not an appropriate method of solving these type of problems.

You can modify Dijksta's algorithm as well, but it needs to change the graph. Modified graph will contain |V|*(S+1) vertices (for every vertex and every possible path length). This answer has a detailed explanation of the graph construction.

DAle
  • 8,990
  • 2
  • 26
  • 45