C Program to implement Prim's Algorithm
Program
#include<stdio.h>
int n, cost[10][10];
void prim()
{
int i, j, startVertex, endVertex;
int k, nr[10], temp, minimumCost = 0, tree[10][3];
temp = cost[0][0];
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (temp > cost[i][j])
{
temp = cost[i][j];
startVertex = i;
endVertex = j;
}
}
}
tree[0][0] = startVertex;
tree[0][1] = endVertex;
tree[0][2] = temp;
minimumCost = temp;
for (i = 0; i < n; i++)
{
if (cost[i][startVertex] < cost[i][endVertex])
nr[i] = startVertex;
else
nr[i] = endVertex;
}
nr[startVertex] = 100;
nr[endVertex] = 100;
temp = 99;
for (i = 1; i < n - 1; i++)
{
for (j = 0; j < n; j++)
{
if (nr[j] != 100 && cost[j][nr[j]] < temp)
{
temp = cost[j][nr[j]];
k = j;
}
}
tree[i][0] = k;
tree[i][1] = nr[k];
tree[i][2] = cost[k][nr[k]];
minimumCost = minimumCost + cost[k][nr[k]];
nr[k] = 100;
for (j = 0; j < n; j++)
{
if (nr[j] != 100 && cost[j][nr[j]] > cost[j][k])
nr[j] = k;
}
temp = 99;
}
printf("The min spanning tree is:\n");
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < 3; j++)
printf("%d\t", tree[i][j]);
printf("\n");
}
printf("Min cost : %d\n", minimumCost);
}
void main()
{
int i, j;
printf("Enter the no. of vertices :\n");
scanf("%d", &n);
printf("Enter the costs of edges in matrix form :\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &cost[i][j]);
}
}
printf("The matrix is :\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d\t", cost[i][j]);
}
printf("\n");
}
prim();
}
Output
Enter the no. of vertices :
4
Enter the costs of edges in matrix form :
99 3 6 8
1 99 5 4
2 9 99 6
4 2 7 99
The matrix is :
99 3 6 8
1 99 5 4
2 9 99 6
4 2 7 99
The min spanning tree is:
1 0 1
2 0 2
3 1 2
Min cost : 5