#include<iostream.h>
#include<conio.h>
class path
{
private:
int i,j,m,n,b[50],cost[20][20],k,d[50];
int u,v,w,num,s[20];
public:
void getdata();
void sp();
void display();
};
void path::getdata()
{
cout<<"\n****SINGLE SOURCE SHORTEST PATH****\n";
cout<<"\nEnter the number of nodes : ";
cin>>n;
cout<<"\nEnter the cost\n";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
cost[i][j]=0;
else
{
cout<<"\ncost["<<i<<","<<j<<"]:";
cin>>cost[i][j];
}
}
cout<<"\n";
}
}
void path::sp()
{
k=1;
clrscr();
cout<<"\nThe cost of vertices are\n";
cout<<"\t";
for(i=1;i<=n;i++)
cout<<i<<"\t";
cout<<"\n\t";
for(i=1;i<=n;i++)
{
cout<<i<<"\t";
for(j=1;j<=n;j++)
cout<<cost[i][j]<<"\t";
cout<<"\n";
}
cout<<"\nEnter the source vertex:";
cin>>v;
for(i=1;i<=n;i++)
{
s[i]=0;
d[i]=cost[v][i];
}
s[v]=1;
b[k++]=v;
d[v]=0;
for(num=2;num<=n;num++)
{
m=9999;
for(j=1;j<=n;j++)
{
if((m>d[j])&&(s[j]==0))
{
m=d[j];
u=j;
}
}
s[u]=1;
b[k++]=u;
for(w=1;w<=n;w++)
{
if(d[w]>(d[u]+cost[u][w])&&(s[w]==0))
d[w]=(d[u]+cost[u][w]);
}
cout<<"\n";
}
}
void path::display()
{
cout<<"\n";
cout<<"\nThe shortest path with source vertex"<<v<<"is\n";
cout<<"\n\t\t"<<b[1];
for(i=2;i<k;i++)
cout<<"----->"<<b[i];
}
void main()
{
clrscr();
path p;
p.getdata();
p.sp();
p.display();
getch();
}
Single Source Shortest Path
Share This!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment