4

I'm editing Floyd's algorithm so instead of each Dk where k is the highest intermediate vertex, k is the max path length. Eventually it will have the same output as Floyd's, but every subiteration could be different. For instance, if there are 4 vertices: 0,1,2,3, I want to find the cheapest path from 0 to 3 that has a max length of K. The graph is assumed directed.

So if k=2, then I could only check 0->3...0->1->3...0->2->3 where every arrow indicates an edge/path. If k=3, then I could only check 0->3...0->1->3...0->1->2->3...0->2->3...0->2->1->3, etc...

    0   1   2   3
0   0   4   9   12
1   9   0   3   11   // the adj matrix I'm referencing for 1 example
2   9   10  0   2
3   1   99  6   0

I need help understanding the implementation in this and am not sure where to start, aside from Floyd's algorithm.

gooberdope
  • 75
  • 1
  • 3
  • 13

1 Answers1

0

Here is Sample C++ code for your problem:

#define INF 100000005

using namespace std;

int main()
{
   int i,j,k,n,m,ver,edg,len,from,to;
   int mat[10][10][10],next[10][10][10];
   cin>>ver;
   for(i=0;i<ver;i++)
   {
       for(j=0;j<ver;j++)
       {
           for(k=0;k<ver;k++)
            {
                mat[i][j][k]=INF;
                next[i][j][k]=j;
            }
       }
   }
   for(i=0;i<ver;i++)
   {

       for(j=0;j<ver;j++)
       {
           cin>>mat[i][j][1];
       }
   }
   for(len=2;len<ver;len++)
   {
       for(k=0;k<ver;k++)
       {
           for(i=0;i<ver;i++)
           {
               for(j=0;j<ver;j++)
               {
                   if(mat[i][k][len-1]+mat[k][j][1]<mat[i][j][len])
                   {
                       mat[i][j][len]=mat[i][k][len-1]+mat[k][j][1];
                       next[i][j][len]=next[i][k][len-1];
                   }
               }
           }
       }
   }
   if(mat[0][3][3]!=INF)
   {
       cout<<"Minimum Cost from 0 to 3,using exactly 3 pathlen is: "<<mat[0][3][3]<<endl;
       from=0;
       to=3;
       len=3;
       cout<<from;
       while(from!=to)
       {
           from=next[from][to][len--];
           cout<<"-->"<<from;
       }
   }
   else
       cout<<"No path"<<endl;
}