Skip to content

Commit 50ebcf9

Browse files
committed
Minimum Spanning Tree: Prim's Algorithm
1 parent 2dfffad commit 50ebcf9

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#include <stdio.h>
2+
3+
#define I 32767
4+
5+
// Algorithm:
6+
/**
7+
* 1. First select vertices having minimum edge cost from cost matrix
8+
* 2. Select the adjacent Vertices having minimum edge cost
9+
*/
10+
11+
// Initialization
12+
int cost[8][8] = {
13+
{I, I, I, I, I, I, I, I},
14+
{I, I, 25, I, I, I, 5, I},
15+
{I, 25, I, 12, I, I, I, 10},
16+
{I, I, 12, I, 8, I, I, I},
17+
{I, I, I, 8, I, 16, I, 14},
18+
{I, I, I, I, 16, I, 20, 18},
19+
{I, 5, I, I, I, 20, I, I},
20+
{I, I, 10, I, 14, 18, I, I}
21+
};
22+
23+
// Initialize as Infinity
24+
int near[8] = {I, I, I, I, I, I, I, I};
25+
26+
// n-> nodes , n-1 -> edges(6)
27+
int t[2][6];
28+
29+
int main(){
30+
int i, j, u, v, k,min = I, n=7, sum=0;
31+
32+
// Initial work
33+
// Find minimum edge from Cost matrix(upper triangular)
34+
for(i = 1; i<=n;i++){
35+
for(j = i; j<=n ;j++){
36+
if(cost[i][j] < min){
37+
min = cost[i][j];
38+
u = i; v = j;
39+
}
40+
}
41+
}
42+
43+
near[u] = near[v] = 0;
44+
t[0][0] = u; t[1][0] = v;
45+
sum += min;
46+
47+
// Identify near vertex having minium edge and connected by the selected edge
48+
for (i = 1; i <= n; i++) {
49+
if (near[i] != 0) {
50+
near[i] = (cost[i][u] < cost[i][v]) ? u : v;
51+
}
52+
}
53+
54+
// Repeatetion work
55+
for(i=1; i<n-1 ;i++){
56+
min = I;
57+
// Identify min edge from near array
58+
for(j=1; j<=n; j++){
59+
if(near[j]!=0 && cost[j][near[j]]<min){
60+
min = cost[j][near[j]];
61+
k = j;
62+
}
63+
}
64+
65+
// update Spanning tree and near array too
66+
t[0][i] = k; t[1][i] = near[k];
67+
near[k] = 0;
68+
sum += min;
69+
70+
// Identify near vertex having minium edge and connected by the selected edge
71+
for(j=1; j<=n; j++){
72+
if(near[j]!=0 && cost[j][k] < cost[j][near[j]]){
73+
near[j] = k;
74+
}
75+
}
76+
}
77+
78+
for(i=0; i<n-1;i++){
79+
printf("(%d, %d),",t[0][i],t[1][i]);
80+
}
81+
82+
printf("\nTotal cost: %d",sum);
83+
84+
return 0;
85+
}
Binary file not shown.

0 commit comments

Comments
 (0)