Sunday, December 12, 2010

Dijkstra's Algorithm

//Program to illustrate Dijkstra's Algorithm

#include
#include
#include
#include

class dijkstra
{
int node[50], pred[50],dist[50],status[50],path[50];
int n,source,dest,adj[50][50],i,j,k,x,temp;
int infinity;

public:

dijkstra()
{
infinity=10000;
}
void read();
void process();
void display();
};

void dijkstra::read()
{
system("clear");
cout<<"Enter the number of nodes: ";
cin>>n;
cout<<"Enter the source node :";
cin>>source;
cout<<"Enter the destination node:";
cin>>dest;
if(source==dest)
{
cout<<"Source and Destination are same";
exit(0);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cout<<"Destination of "< cin>>adj[i][j];
}
pred[i]=0;
status[i]=0;
dist[i]=infinity;
node[i]=i;
}
process();

}

void dijkstra::process()
{
dist[source]=0;
temp=source;
status[source]=1;
for(x=1;x<=n;x++)
{
for(j=1;j<=n;j++)
if((adj[source][j]!=0) && (status[j]==0))
{
pred[j]=node[source];
dist[j]=dist[source]+adj[source][j];
}
infinity=10000;
for(k=1;k<=n;k++)

if(status[k]==0)
if(dist[k] {
infinity=dist[k];
source=node[k];
}
if(source==dest)
break;
else
{
status[source]=1;
}
}

path[1]=dest;
k=2;
for(i=1;i<=n;i++)
{
path[k]=pred[dest];
dest=pred[dest];
k++;
if(dest==temp)
break;
}
}

void dijkstra::display()
{
cout<<"Shortest path is:";
for(k=i+1;k>=1;k--)
cout<<"-->"< cout<<"\n";
}

void main()
{
clrscr();

dijkstra d;
d.read();
d.display();
getch();
}


OUTPUT

Enter the number of nodes: 3
Enter the source node :1
Enter the destination node:2
Destination of 1th node to 1th node:4
Destination of 1th node to 2th node:20
Destination of 1th node to 3th node:3
Destination of 2th node to 1th node:2
Destination of 2th node to 2th node:4
Destination of 2th node to 3th node:4
Destination of 3th node to 1th node:1
Destination of 3th node to 2th node:2
Destination of 3th node to 3th node:2
Shortest path is:-->1-->3-->2

No comments:

Post a Comment