Dijkstra's Algorithm
#include<stdio.h>
void dijkstra(int);
int search_min(int [100],int [100]);
int adjmat[100][100],n;
int main()
{
int s,i,j;
printf("Enter number of vertices?\n");
scanf("%d",&n);
printf("enter adjacensy matrix?\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&adjmat[i][j]);
}
}
printf("Enter source vertex?\n");
scanf("%d",&s);
dijkstra(s);
}
void dijkstra(int s)
{
int set[100],length[100],path[100];
int i=0,j,complete;
while(i<n)
{
set[i]=0;
i++;
}
i=0;
while(i<n)
{
if(adjmat[s][i]==0)
{
length[i]=999;
path[i]=999;
}
else
{
length[i]=adjmat[s][i];
path[i]=s;
}
i++;
}
set[s]=1;
length[s]=0;
complete=0;
while(complete==0)
{
i=search_min(length,set);
set[i]=1;
j=0;
while(j<n)
{
if(set[j]==1)
j++;
else
{
if(adjmat[i][j]!=0)
{
if((length[i]+adjmat[i][j])<length[j])
{
length[j]=length[i]+adjmat[i][j];
path[j]=i;
}
}
j++;
}
}
complete=1;
i=0;
while(i<n)
{
if(set[i]==0)
{
complete=0;
break;
}
else
{
i++;
}
}
}
printf("source->dest\tpath\tlength\n");
for(i=1;i<n;i++)
{
printf("v%d->v%d\t\t",s,i);
j=i;
while(j!=s)
{
printf("v%d-",j);
j=path[j];
}
printf("v%d\t\t%d\n",s,length[i]);
}
}
int search_min(int length[100],int set[100])
{
int min=999;
int i=-1,ind=-1;
for(i=0;i<n;i++)
{
if(set[i]==0)
{
if(min>length[i])
{
min=length[i];
ind=i;
}
}
}
return ind;
}
Output
No comments:
Post a Comment