Skip to content

Commit a619cde

Browse files
Program to implement kruskals algorithm
1 parent 5f6ae77 commit a619cde

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

spantree_kruskals.c

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
int i,j,k,a,b,u,v,n,ne=1;
4+
int min,mincost=0,cost[9][9],parent[9];
5+
int find(int);
6+
int uni(int,int);
7+
void main()
8+
{
9+
printf("\nImplementation of kruskals Algorithm:\n");
10+
printf("\nEnter the no.of vertices:");
11+
scanf("%d",&n);
12+
printf("\nEnter the cost adjacency matrix:\n");
13+
for(i=1;i<=n;++i)
14+
{
15+
for(j=1;j<=n;++j)
16+
{
17+
scanf("%d",&cost[i][j]);
18+
if(cost[i][j]==0)
19+
cost[i][j]=999;
20+
}
21+
}
22+
printf("The edges if minimun cost spanning tree are:\n") ;
23+
while(ne<n)
24+
{
25+
for(i=1,min=999;i<n;++i)
26+
{
27+
for(j=1;j<=n;j++)
28+
{
29+
if(cost[i][j]<min)
30+
{
31+
min=cost[i][j];
32+
a=u=i;
33+
b=v=j;
34+
}
35+
}
36+
}
37+
u=find(u);
38+
v=find(v);
39+
if(uni(u,v))
40+
{
41+
printf("%d edge(%d,%d)=%d\n",ne++,a,b,min);
42+
mincost+=min;
43+
}
44+
cost[a][b]=cost[b][a]=999;
45+
}
46+
printf("\nMinimum cost =%d\n",mincost);
47+
}
48+
int find(int i)
49+
{
50+
while(parent[i])
51+
i=parent[i];
52+
return i;
53+
}
54+
int uni(int i,int j)
55+
{
56+
if(i!=j)
57+
{
58+
parent[j]=i;
59+
return 1;
60+
}
61+
return 0;
62+
}

0 commit comments

Comments
 (0)