You are on page 1of 2

//PROGRAM FOR DIJKSTRA'S ALGORITHM

#include<iostream.h>
#include<conio.h>
int cost[50][50],b[50],dist[50],n;
int find(int*,int*,int);
void main()
{ clrscr();
int i,j,num,v,u;
cout<<"enter the no of nodes in the graph : "<<endl;
cin>>n;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cost[i][j]=0;
}
cout<<"\nenter the weights of the graph : (Enter 1000 if no edge exists between 2
nodes) ";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cin>>cost[i][j];
}
//print the cost matrix in matrix form
for(i=1;i<=n;i++)
{ cout<<endl;
for(j=1;j<=n;j++)
cout<<"\t"<<cost[i][j];
}
for(i=1;i<=n;i++)
b[i]=0; //initialise b[] matrix to 0
cout<<"\ninput the source vertex : ";
cin>>v;
for(i=1;i<=n;i++)
{
dist[i]=cost[v][i];
b[v]=1;
dist[v]=0;
}
for(num=2;num<=n-1;num++)
{
u=find(dist,b,n);
b[u]=1;

for(int w=1;w<=n;w++)
{
if((cost[u][w]!=1000 )&& b[w]==0)
{
if(dist[w]> dist[u]+cost[u][w])
{
dist[w]=dist[u]+cost[u][w];
}
}
}
}
cout<<"the distance matrix is :\n ";
for(i=1;i<=n;i++)
cout<<" "<<dist[i];
getch();
}
int find(int dist[],int s[],int n)
{
int u,i;
int min=1000;
for(i=1;i<=n;i++)
{
if(s[i]==0 && dist[i]<min)
{
min=dist[i];
u=i;
}
}
return(u);
}

You might also like