Saturday, May 8, 2021

50.4. C Programming code for Djikstra Algorithm.

#include<stdio.h>

void djikstra()
{
int start,dest = n,min_cost,curr,i,j;
printf("\nEnter starting vertex ");
scanf("%d",&start);
vis[start]=1;
for(i=1;i<=n;i++)
{
if(i!=start)
{
vis[i]=0;
from[i]=start;
cost[i]=cost_mat[start][i];
}
}
for(i=1;i<n;i++)
{
min_cost = 999;
 
for(j=1;j<=n;j++)     
{
if(vis[j]==0 && cost[j]<min_cost)
{
min_cost = cost[j];
curr = j;
}

vis[curr]=1;
if(curr==dest)
break;
for(j=1;j<=n;j++)                          
{
if(vis[j]==0 && (cost_mat[curr][j]+min_cost) < cost[j])
{
from[j] = curr;
cost[j] = cost_mat[curr][j]+min_cost;
}
}
}
printpath(start,dest);
printf("\nMin cost = %d",cost[dest]);
}
void printpath(int start,int dest)
{
if(dest==start)
{
printf("%d  ",start);
return;
}
printpath(start,from[dest]);
printf("%d  ",dest);

}

No comments:

Post a Comment