We observe that the problem is similar to all pairs shortest path problem, but in addition to that, we have the constraint that we can go through at most m astro-haunted galaxies. We model this constraint also in our notation.
Notation Let D(i,j,k) denote the cost of the shortest path from i to j using at most k astro-haunted galaxies.
Recursive Formulation Recursive formulation on D(i,j,k) can be written on the variable k and by deciding on the last astro-haunted galaxy on the path from i to j . D(i,j,k) = min { D(i,j,k-1), min (1≤z≤n | A[z]=1 ) {D(i,z,k-1) + D(z,j,0)} } We observe that A[z] = 1 constraint specifies that the galaxy z is astro haunted.
Further, by taking the minimum with D(i,j,k-1) we satisfy the constraint of at most k astro-haunted galaxies, while still avoiding pitfall of leaving this value undefined in case there is no astro haunted galaxy.
Base Case D(i,j,0) can be solved simply by using All Pairs Shortest Path and by eliminating all astro-haunted galaxies.
Algorithm The algorithm can easily be written in terms of for loops for each of the indices in the notation of D(i,j,k) . As is often observed, the index of the main recursive formulation usually forms the outermost loop.
// Step 1: Base Case
Calculate D[i][j][0] as All Pairs Shortest path by ignoring the astro haunted galaxies.
// Step 2: Inductive Step
for k = 1 to m
for i = 1 to n
for j = 1 to n
Calculate D[i][j][k] = min {D([i][j][k-1], D[i][z][k-1] + D[z][j][0] for all z such that A[z] = 1}
Time Complexity
Time Complexity of base case: O(n^3 ) from the all pairs shortest path problem. Each calculation of D(i,j,k) takes O(n) time. Further, there are kn^2 entries in the dynamic programming table. Therefore, the total time Complexity of recursive portion: O(k n^3) Therefore, the total time complexity is O(k n^3 ).