#include<conio.h>
#include<stdio.h>
#define INFNITY 999
int a[10][10],p[10],d[10],n;
voidprintArray(){
inti,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
}
voiduAdjacencyMatrix(){
inti,j,c=1,w;
for(i = 0;i < n; i++)
{
for(j = 0;j < i; j++)
{
a[i][j] = INFNITY;
a[j][i] = INFNITY;
}
a[i][i] = INFNITY;
}
while(c!=-1)
{
printf ("\ni , j , w :");
scanf("%d%d%d",&i,&j,&w);
a[i][j]=w;
//printf
("c? :");
scanf("%d",&c);
}
printArray();
getch();
}
voidinitializeSingleSource(int i)
{
int j;
for(j=0;j<n;j++)
{
p[j]=-1;
d[j]=INFNITY;
}
d[i]=0;
}
voidtracePath(int a)
{
if(p[a]!=-1)
tracePath(p[a]);
printf("-->%d",a);
}
voidshowAllPaths()
{
int i;
for(i=0;i<n;i++)
{
if(p[i]!=-1)
printf("\n%d-->%d",p[i],i);
}
}
int main()
{
inti,j,k;
printf("enter the number of vertices : ");
scanf("%d",&n);
uAdjacencyMatrix();
printf("enter the
source vertex : ");
scanf("%d",&i);
initializeSingleSource(i);
for(i=0;i<n-1;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
if((a[j][k]!=INFNITY)&& d[k]>d[j]+a[j][k])
{
p[k]=j;
d[k]=d[j]+a[j][k];
}
}
}
}
int t=0;
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
if((a[j][k]!=INFNITY)&& d[k]>d[j]+a[j][k])
{
t=-1;
}
if(t==-1)
break;
}
if(t==-1)
break;
}
if(t==-1)
printf("\nexiting");
showAllPaths();
printf("\n Enter the vertex for shortest path :
");
scanf("%d",&i);
tracePath(i);
getch();
return(0);
}
No comments:
Post a Comment