Tuesday, February 07, 2012

Directed path Floyd_Warshall algorithm

/***
    For Directed path Floyd_Warshall algorithm
Author : Md.Saiful Islam
***/
#include<stdio.h>
#define NIL 0
#define INF 99999


int cost[1008][1008],path[109][109];


void init(int n)
{
int i,j;
for(i=0;i<=n;i++)
{
for(j=0;j<=n;j++)
{
if(i == j)
cost[i][j] = NIL;
else cost[i][j] = INF;


path[i][j] = NIL; //to print path
}
}
return ;
}


void Floyd_Warshall(int n)
{
int i,j,k;
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j] > cost[i][k] + cost[k][j])
{
cost[i][j] = cost[i][k] + cost[k][j];
path[i][j] = path[k][j]; // to print path
}
}
}
}
return ;
}




void print_matrix_path(int n)
{
int i,j;


printf("\ndistance matrix:\n");


for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d ",cost[i][j]);
}
printf("\n");
}
printf("PATH matrix :\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d ",path[i][j]);
}
printf("\n");
}
}


void print_path(int s,int e)
{
if(path[s][e]==s)
{
printf("%d",path[s][e]);
return;
}
else if(path[s][e]==0)
{
printf("No path");
//pik=5;
}
else
{
print_path(s,path[s][e]);
printf(" %d",path[s][e]);
}
return;
}


int main()
{
int i,node,edge,s,e,t,a,b,c,j;
while(scanf(" %d%d",&node,&edge)==2 && (node || edge))
{
init(node);


for(i=1;i<=edge;i++)
{
scanf("%d%d%d",&a,&b,&c);
cost[a][b] = c;
}


//for print path && cycle


for(i=1;i<=node;i++)
{
for(j=1;j<=node;j++)
{
if(cost[i][j]!=INF  && i!=j)
{
path[i][j]=i;
}
}
}


Floyd_Warshall(node);


print_matrix_path(node);


scanf(" %d",&t);
while(t--)
{
scanf(" %d %d",&s,&e);


printf("saif\n");


print_path(s,e);


printf("%d\n",cost[s][e]);
}
}
return 0;
}

No comments:

Post a Comment