#include<iostream.h>
#include<conio.h>
#define inf 333
class mst
{
int n,e,k,mincost,cost[10][10];
public:
mst()
{
n=0;
e=0;
k=0;
mincost=0;
}
void read();
void spantree();
void display();
};
void mst::read()
{
int i,j,z;
cout<<"Enter the no of Vertices\n";
cin>>n;
for(i=1;i<=n;i++)
cost[i][0]=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j]=inf;
cout<<"Enter the Cost Matrix\n";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
cout<<"["<<i<<","<<j<<"]=";
cin>>z;
if(z)
{
cost[i][j]=cost[j][i]=z;
e++;
}
}
}
void mst::spantree()
{
int i,j,row,col,flag;
int min=inf;
cost[1][0]=1;
while(k<n-1 && e!=0)
{
flag=0;
min=inf;
for(i=1;i<=n;i++)
if(cost[i][0]==1)
{
for(j=1;j<=n;j++)
{
if(cost[j][0]==0 && cost[i][j]<min)
{
min=cost[i][j];
col=j;
flag=1;
}
}
}
if(flag)
{
k++;
mincost=mincost+min;
cost[col][0]=1;
e--;
}
}
}
void mst::display()
{
if(k!=n-1)
cout<<"No Spanning Tree\n";
else
cout<<"Cost Of MST: "<<mincost;
}
void main()
{
mst s;
clrscr();
cout<<"Minimum Spanning Tree\n\n";
s.read();
s.spantree();
s.display();
getch();
}
Comments
Post a Comment