Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Wednesday, 27 March 2019

Kruskal's algorithm

ALGORITHM Kruskal(G)

//Kruskal’s algorithm for constructing a minimum spanning tree

//Input: A weighted connected graphV, E

//Output: Ethe set of edges composing a minimum spanning tree of Gsort in nondecreasing order of the edge weights w(ei1≤ . . . ≤ w(ei|E|)
E← ecounter ← 0 //initialize the set of tree edges and its size

← 0 //initialize the number of processed edges

while ecounter < || - do← 1

if E∪ {eikis acyclicE← E∪ {eik}ecounter ← ecounter 1

return ET 


C program: 

#include<stdio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
int main()
{

printf("\n\tImplementation of Kruskal's algorithm\n");
printf("\nEnter the no. of vertices:");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{  printf("\nEnter connection bt vertex %c & vertex %c\t",i+64,j+64);
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("The edges of Minimum Cost Spanning Tree are\n");
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j <= n;j++)
{
if(cost[i][j] < min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("%d edge (%c,%c) =%d\n",ne++,64+a,64+b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost = %d\n",mincost);
}

int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

Output:

 Implementation of Kruskal's algorithm

Enter the no. of vertices:4

Enter the cost adjacency matrix:

Enter connection bt vertex A & vertex A 0

Enter connection bt vertex A & vertex B 5

Enter connection bt vertex A & vertex C 999

Enter connection bt vertex A & vertex D 3

Enter connection bt vertex B & vertex A 5

Enter connection bt vertex B & vertex B 0

Enter connection bt vertex B & vertex C 3

Enter connection bt vertex B & vertex D 999

Enter connection bt vertex C & vertex A 999

Enter connection bt vertex C & vertex B 3

Enter connection bt vertex C & vertex C 0

Enter connection bt vertex C & vertex D 6

Enter connection bt vertex D & vertex A 3

Enter connection bt vertex D & vertex B 999

Enter connection bt vertex D & vertex C 6

Enter connection bt vertex D & vertex D 0
The edges of Minimum Cost Spanning Tree are
1 edge (A,D) =3
2 edge (B,C) =3
3 edge (A,B) =5

Minimum cost = 11



0 comments:

Post a Comment