#include<iostream>
using namespace std;
int cost[20][20];
int main()
{
int i,j,c[10][10],dist[10],s[10];
int temp,tempcost,n,src,minm;
cout<<"\n\nEnter the no. of vertices:";
cin>>n;
cout<<"\nGive the cost:";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
{
c[i][j]=0;
}
else
{
cout<<"Enter the cost:"<<i<<"to"<<j<<"::";
cin>>c[i][j];
}
}
}
cout<<"\nEnter the vertex number to find the shortest path for all paths:";
cin>>src;
cout<<"\nThe adjacency matrix given is:";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cout<<c[i][j]<<"\t";
}
cout<<"\n";
}
for(i=1;i<=n;i++)
{
s[i]=0;
dist[i]=c[src][i];
}
s[src]=1;dist[src]=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(s[j]==0)
{
minm=dist[j];
temp=j;
break;
}
}
}
for(j=1;j<=n;j++)
{
if(s[j]==0 && minm>dist[j])
{
minm=dist[j];
temp=j;
}
}
s[temp]=1;
for(j=1;j<=n;j++)
{
if(s[j]==0)
{
tempcost=dist[temp]+c[temp][j];
if(dist[j]>tempcost)
{
dist[j]=tempcost;
}
}
}
cout<<"\n\nThe vertices are:"<<"\n";
for(i=1;i<=n;i++)
cout<<"\t"<<i;
cout<<"\nThe distances are:"<<"\n";
for(i=1;i<=n;i++)
cout<<dist[i]<<"\t";
return 0;
}
No comments:
Post a Comment