#define max 5
#define infinity 5000
#include<conio.h>
#include<string.h>
#include<stdio.h>
void writeDjikstra(int distances[max][max]);
void Djikstra(int distances[max][max]);
int min(int a,int b);
int distances[5][5];
void writeMatrix(int distances[max][max]);
void readMatrix(int distances[max][max]);
void main()
{
clrscr();
readMatrix(distances);
writeMatrix(distances);
Djikstra(distances);
writeDjikstra(distances);
getch();
}
void writeDjikstra(int distances[max][max])
{
int row;
printf("\n\nSolution is ");
for(row=1;row<=max-1;row++)
printf("\ndistance from A to %c is %6d",'A' + row,distances[0][row]);
}
void Djikstra(int distances[max][max])
{
int row,col,d;
for(row=1;row<=max-1;row++)
{
for(col=0;col<=max-1;col++)
{
d=min(distances[0][row],distances[0][col]+distances[col][row]);
distances[0][row]=d;
distances[row][0]=d;
}
}
}
int min(int a,int b)
{
if(a<b)
return(a);
else
return(b);
}
void writeMatrix(int distances[max][max])
{
int row,col;
printf("\n\nDistance matrix =\n");
for(row=0;row<=max-1;row++)
{
for(col=0;col<=max-1;col++)
printf("%6d",distances[row][col]);
printf("\n");
}
}
void readMatrix(int distances[max][max])
{
int row,col;
for(row=0;row<=max-1;row++)
{
for(col=0;col<=max-1;col++)
{
if(row==col)
{
distances[row][col]=0;
continue;
}
if(col>row)
{
printf("Enter negative number for infinity,Distance from %c to %c = ",'A' + row,`A` + col);
scanf("%d",&distances[row][col]);
if(distances[row][col]<0)
distances[row][col]=infinity;
}
else
{
distances[row][col]=distances[col][row];
}
}
}
}
No comments:
Post a Comment