Sunday, October 18, 2015

C Program to count all possible path from source to destination in a Graph using adjacency matrix.

/* =====================================================================================
 * *
 * *       Filename :  pathcountgraph.c
 * *       Created    :  Tuesday 27 January 2015 17:30:17  IST
 * *       Compiler :  gcc
 * *       Author     :  Manoj Kumar Patra,manojpatra.sit@gmail.com
 * *   Organization:  SCIS,University of Hyderabad
 * *
 * * =====================================================================================*/

#include <stdio.h>

int main()
{
int pl,i,n,c, d, k,source,dest,sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("\nEnter the number of nodes:");
scanf("%d", &n);
printf("\n=======================================\n");
printf("Enter the edge(path) of the graph\n");
printf("ENTER '1' if yes, ENTER '0' if no path\n");
printf("\n=======================================\n");

for(c=0;c<n;c++)
{
for(d=0;d<n;d++)
{
first[c][d]=second[c][d]=0;
}
}

for(c=0;c<n;c++)
{
for(d=0;d<n;d++)
{
if(c==d)
continue;
if(first[d][c]==1)
continue;
printf("Is there any path from node '%d' to node '%d':",c+1,d+1);
scanf("%d", &first[c][d]);
second[c][d]=first[c][d];
}
printf("\n");
}

printf("\nThe Adjecency Matrix:\n");
printf("---------------------\n");
for(c=0;c<n;c++)
{
for(d=0;d<n;d++)
{
printf("%d\t",first[c][d]);
}
printf("\n");
}

printf("\n----------------------\n");

printf("\nEnter the length of the path:");
scanf("%d",&pl);

for(i=pl-1;i>0;i--)
{
for(c=0;c<n;c++)
{
for(d=0;d<n;d++)
{
for(k=0;k<n;k++)
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
for(c=0; c<n; c++)
{
for(d=0; d<n; d++)
{
second[c][d]=multiply[c][d];
}
}
}
printf("\nThe resultant matrix is:\n");
for (c=0; c<n; c++)
{
for (d=0; d<n; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
printf("\nEnter the source:");
scanf("%d",&source);
printf("Enter the destination:");
scanf("%d",&dest);
if(multiply[source-1][dest-1]>0)
{
printf("\nNumber of path from node '%d' to node '%d' is:%d\n",source,dest,multiply[source-1][dest-1]);
}
else
{
printf("\nNo path from nade '%d' to node '%d' ...!!!\n",source,dest);
}

printf("\n");

return 0;
}

No comments:

Post a Comment