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

ADA Lab Program 1

The document describes a laboratory program for the Analysis & Design of Algorithms course (BCSL404) that involves implementing Kruskal’s algorithm to find the Minimum Cost Spanning Tree of a connected undirected graph. It includes a C/C++ code snippet that prompts the user for the number of vertices and a cost matrix, then calculates and displays the edges of the spanning tree along with the minimum cost. The program uses a parent array to track connected components and outputs the edges and total minimum cost after execution.
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)
5 views

ADA Lab Program 1

The document describes a laboratory program for the Analysis & Design of Algorithms course (BCSL404) that involves implementing Kruskal’s algorithm to find the Minimum Cost Spanning Tree of a connected undirected graph. It includes a C/C++ code snippet that prompts the user for the number of vertices and a cost matrix, then calculates and displays the edges of the spanning tree along with the minimum cost. The program uses a parent array to track connected components and outputs the edges and total minimum cost after execution.
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

Analysis & Design of Algorithms Lab (BCSL404)

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

Code:
#include<stdio.h>
int ne=1, min_cost=0;
void main()
{
int n,i,j,min,a,u,b,v,cost[20][20],parent[20];
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("\nEnter the cost matrix: \n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d", &cost[i][j]);
for(i=1;i<=n;i++)
parent[i]=0;
printf("\n The edges of spanning tree are\n");
while(ne<n)
{
min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
while(parent[u])
u=parent[u];
while(parent[v])
v=parent[v];
if(u!=v)
{
printf("Edge %d\t(%d->%d)=%d\n",ne++,a,b,min);
min_cost=min_cost+min;
parent[v]=u;
}
cost[a][b]=cost[a][b]=999;
}
printf("\n Minimum cost=%d\n",min_cost);
}
Output:

You might also like