0% found this document useful (0 votes)
2 views

Program 1

The document provides a C/C++ program that implements Kruskal's algorithm to find the Minimum Cost Spanning Tree of a connected undirected graph. It includes functions for finding the minimum edge, checking for cycles, and calculating the total cost of the spanning tree. A sample input and output demonstrate the program's functionality with a graph of four vertices.

Uploaded by

vijethviju04
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 views

Program 1

The document provides a C/C++ program that implements Kruskal's algorithm to find the Minimum Cost Spanning Tree of a connected undirected graph. It includes functions for finding the minimum edge, checking for cycles, and calculating the total cost of the spanning tree. A sample input and output demonstrate the program's functionality with a graph of four vertices.

Uploaded by

vijethviju04
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/ 2

Program 1

Design and implement C/C++ Program to find Minimum Cost Spanning Tree
of a given connected undirected graph using Kruskal's algorithm.

#include<stdio.h>
int min=0,cost[10][10],parent[10],i,j,x,y,n;
void main()
{
int count=0,tot=0,flag=0;
void find_min();
int check_cycle();
printf("enter the no of vertices\n");
scanf("%d",&n);
printf("enter the matrix\n");
printf("enter 999 for self loops and no edge\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("%d-->%d=%d\n",x,y,cost[x][y]);
count++;
tot+=cost[x][y];
}
cost[x][y]=cost[y][x]=999;
}
printf("the total cost=%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[y]=parent[x];
else if(parent[y]==0)
parent[y]=parent[x];
else if(parent[x]!=parent[y])
parent[y]=parent[x];
return 1;
}

Sample Input and Output:


enter the no of vertices
4
enter the matrix
enter 999 for self loops and no edge
999 1 5 2
1 999 999 999
5 999 999 3
2 999 3 999
1-->2=1
1-->4=2
3-->4=3
the total cost=6

You might also like