Dijkstra Algorithm code (using Global variables)
#include<bits/stdc++.h>
#include<limits.h>
using namespace std;
#define V 9
void print_dijkstra(int dst[V])
{
int i;
cout<<"NODE\tdst\n";
for(i=0;i<V;i++)
cout<<i<<"\t"<<dst[i]<<endl;
}
int mindst(int dst[V], bool mstset[V])
{
int min=INT_MAX, min_index,i;
for(i=0;i<V;i++)
{
if(mstset[i]==false && dst[i]<min)
{
min=dst[i];
min_index=i;
}
}
return min_index;
}
void dijkstra(int graph[V][V])
{
int dst[V], i, edge,x,u;
bool mstset[V];
for(i=0;i<V;i++)
{
dst[i]=INT_MAX;
mstset[i]=false;
}
cout<<"Enter the satarting node : ";
cin>>x;
dst[x]=0;
// number of edges should be 1 less than the number of vertices;
for(edge=0;edge<V-1;edge++)
{
u=mindst(dst, mstset);
mstset[u]=true;
//update the distance of those adjacent vertices who are not the part of mstset yet;
for(i=0;i<V;i++)
{
if(mstset[i]==false && dst[u]!=INT_MAX && graph[u][i]!=0 && graph[u][i]+dst[u]<dst[i])
dst[i]=dst[u]+graph[u][i];
}
}
print_dijkstra(dst);
}
int main()
{
int graph[V][V]={ { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph);
return 0;
}
Comments
Post a Comment