0

Someone can give to me the time complexity of this procedure inside the for iteration? This piece of code is the "reconstruction path" part of FloydWarshall algorithm. prev[n][n] is the matrix of the nodes that are between source node and destination in the shortest path. printAllSP runs n^2 times in the iteration, what i can't really figure out is the number of recursive calls that it does every time, only understood that depends by i value (max n), j value(max n) and the number of k (???) nodes that interject in the shortest path between i and j, by my evaluations including the for cycles this part runs in On^4 but the total algorithm complexity is On^3.Enlight me pls!

 void PrintAllSP(int i, int j, int prev[n][n]){
if (i == j)
    print i
else  {
    PrintAllSP(i, prev[i][j], prev);
    print j
}
}

//PSEUDOPART OF MAIN
for i = 1 TO n
    for j = 1 TO n
        PrintAllSP(i, j, prev);
    }
}
Vignusky
  • 21
  • 4

1 Answers1

2

There are n nodes total, which means O(n^2) shortest paths are printed. Each shortest path can only have up to n nodes in it. Therefore, only O(n^3) nodes can be printed. Since each base recursive step results in one node being printed, this means only O(n^3) base recursive steps total.

Sneftel
  • 40,271
  • 12
  • 71
  • 104