Dijsktra Algorithms

#include<stdio.h>
#include<stdlib.h>
#define INF 9999
void main()
{
int vc,**el,**res;
int i,j,k;
char ch=’y’;
clrscr();
while(ch==’y’||ch==’Y’)
{
printf(“Enter the no of vertices:”);
scanf(“%d”,&vc);
el = (int **)calloc(sizeof(int),  vc);
res = (int **)calloc(sizeof(int), vc);
for (i=0;i<vc;i++)
{
el[i] = (int *)calloc(sizeof(int),  vc);
res[i] = (int *)calloc(sizeof(int), vc);
}

/* Adjacency Matrix to store Cost of the edges */
for (i=0;i<vc;i++)
{
for (j=0;j<vc;j++)
{
printf(“Edge weight %d to %d (0 if no edge):”,i+1,j+1);
scanf(“%d”,&el[i][j]);
if(el[i][j] == 0)
{
res[i][j] = INF;
}
else
{
res[i][j] = el[i][j];
}
}
}
printf(“Adjacent matrix for edge weights:\n”);
printf(”   “);
for(i=0;i<vc;i++)
printf(“%3d”,i+1);
for(i=0;i<vc;i++)
{
printf(“\n%d |”,i+1);
for(j=0;j<vc;j++)
{
printf(“%3d”,el[i][j]);
}
printf(” |\n”);
}
/* Calculate shortest path from each vertex to every other vertices */
for (i=0;i<vc;i++)
{
for(j=0;j<vc;j++)
{
for(k=0;k<vc;k++)
{
if(res[j][k] > res[j][i] + res[i][k])
{
res[j][k] = res[j][i] + res[i][k];
}
}
}
}
printf(“\nShortest path between vertices\n”);
printf(”   “);
for(i=0;i<vc;i++)
printf(“%3d”,i+1);
for(i=0;i<vc;i++)
{
printf(“\n%d |”,i+1);
for(j=0;j<vc;j++)
{
if(res[i][j] == INF)
printf(“%3d”, 0);
else
printf(“%3d”, res[i][j]);
}
printf(” |\n”);
}
fflush(stdin);
printf(“\nDo you want to continue:(y/n):”);
scanf(“%c”,&ch);
clrscr();
}
getch();
}

Leave a comment