0% found this document useful (0 votes)
2 views3 pages

Kruskals Algorithm

The document describes a C program that implements Kruskal's algorithm to construct a minimum spanning tree for a road network connecting 'n' towns. The program prompts the user for the number of towns and a cost matrix, then calculates and outputs the total cost of the least expensive tree of roads. The final output indicates that the total cost of the minimum spanning tree is 15.

Uploaded by

geetha sree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Kruskals Algorithm

The document describes a C program that implements Kruskal's algorithm to construct a minimum spanning tree for a road network connecting 'n' towns. The program prompts the user for the number of towns and a cost matrix, then calculates and outputs the total cost of the least expensive tree of roads. The final output indicates that the total cost of the minimum spanning tree is 15.

Uploaded by

geetha sree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Lab Program:

A Government wants to construct a road network connecting ‘n’ towns. Suppose each
road must connect ‘2’ towns and be straight. Write a C program using Kruskal’s
algorithm to output the least expensive tree of roads.
#include <stdio.h>
int min, cost[100][100],parent[100],i,j,x,y,n;

void find_min();
int check_cycle(int,int);

void main()
{
int count=0,tot=0,flag=0;
printf("Enter the number of vertices \n");
scanf("%d",&n);
printf("Enter the cost matrix \n");
printf("Enter 999 for No edges and self loops \n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
parent[j]=0;
}
while(count!=n-1 && min!=999)
{
find_min();
flag=check_cycle(x,y);
if(flag==1)
{
printf("\n%d----->%d==%d\n",x,y,cost[x][y]);
count++;
tot+=cost[x][y];
}
cost[x][y]=cost[y][x]=999;
}
printf("\nThe total cost of minimum spanning tree=%d",tot);
}

void find_min()
{
min=999;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
{
min=cost[i][j];
x=i;
y=j;
}
}
int check_cycle(int x,int y)
{
if((parent[x]==parent[y]) && (parent[x]!=0))
return 0;
else if (parent[x]==0 && parent[y]==0)
parent[x]=parent[y]=x;
else if(parent[x]==0)
parent[x]=parent[y];
else if(parent[x]!=parent[y])
parent[y]=parent[x];
return 1;
}

Output:

The total cost of minimum spanning tree=15

You might also like