Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

PAT-2

Manaswi
20BPS1019
Question:

Algorithm used: Prim’s Algorithm


ALGORITHM
START
i. Take the inputs of the no. of nodes and adjcency matrix from the user
ii. choose any vertex.
iii. Find all the edges that connect the tree to new vertices
iv. Find the least weight edge
v. include it in the existing tree
vi. If including that edge creates a cycle, then reject that edge and look for the
next least weight edge
vii. Repeat until all the vertices are included and Minimum Spanning Tree
viii. Print the edges cost of each edge and the minimum cost
END
CODE
#include<stdio.h>
#include<conio.h>
int a,b,x,y,n,i,j,w=1;
int v[10]={0},m,mc=0,c[10][10];
void main()
{
printf("\n number of nodes:");
scanf("%d",&n);
printf("\n adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&c[i][j]);
if(c[i][j]==0)
c[i][j]=999;
}
v[1]=1;
printf("\n");
while(w<n)
{
for(i=1,m=999;i<=n;i++)
for(j=1;j<=n;j++)
if(c[i][j]<m)
if(v[i]!=0)
{
m=c[i][j];
x=a=i;
y=b=j;
}
if(v[a]==0 || v[b]==0)
{
printf("\n Edge %c:(%c %c) cost:%d",96+w++,96+x,96+y,m);
mc+=m;
v[y]=1;
}
c[x][y]=c[y][x]=999;
}
printf("\n Minimum cost=%d",mc);
getch();
}
OUTPUT

You might also like