Krushkals Minimum cost spanning tree
Aim: To implement krushkals algorithm to generate minimum spanning tree
Program:
#include<stdio.h>
int cost[10][10],i,j,k,n,a,b,ne,min=999,set[10],mincost=0,u,v;
void main()
{
clrscr();
printf("minimum cost spanning tree with krushkals");
printf("\nenter no of vertices");
scanf("%d",&n);
printf("\nenter cost matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
for(i=1;i<n;i++)
set[i]=i;
ne=0;
while(ne<n-1)
{
min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=i;
b=j;
}
}
}
u=find(a);
v=find(b);
if(u!=v)
{
unin(u,v);
ne++;
printf("%d edges(%d,%d) is cost is %d\n",ne,a,b,min);
mincost=mincost+min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n total min cost spanning tree is %d",mincost);
getch();
}
int find(int x)
{
return set[x];
}
int unin(int i,int j)
{
int k;
for(k=1;k<=n;k++)
{
if(set[k]==j)
set[k]=i;
}
}
Input:
the input is given in adjacent matrix from for below graph
Output:
No comments:
Post a Comment