-
Notifications
You must be signed in to change notification settings - Fork 0
/
(GRAPH)PRIMSALGORITHM.cpp
94 lines (82 loc) · 2.16 KB
/
(GRAPH)PRIMSALGORITHM.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <bits/stdc++.h>
using namespace std;
#define V 8
#define I 32767
void PrintMST(int T[][V-2], int G[V][V]){
cout << "\nMinimum Spanning Tree Edges (w/ cost)\n" << endl;
int sum {0};
for (int i {0}; i<V-2; i++){
int c = G[T[0][i]][T[1][i]];
cout << "[" << T[0][i] << "]---[" << T[1][i] << "] cost: " << c << endl;
sum += c;
}
cout << endl;
cout << "Total cost of MST: " << sum << endl;
}
void PrimsMST(int G[V][V], int n){
int u;
int v;
int min {I};
int track [V];
int T[2][V-2] {0};
// Initial: Find min cost edge
for (int i =1; i<V; i++){
track[i] = I; // Initialize track array with INFINITY
for (int j =i; j<V; j++){
if (G[i][j] < min){
min = G[i][j];
u = i;
v = j;
}
}
}
T[0][0] = u;
T[1][0] = v;
track[u] = track[v] = 0;
// Initialize track array to track min cost edges
for (int i {1}; i<V; i++){
if (track[i] != 0){
if (G[i][u] < G[i][v]){
track[i] = u;
} else {
track[i] = v;
}
}
}
// Repeat
for (int i=1; i<n-1; i++){
int k;
min = I;
for (int j =1; j<V; j++){
if (track[j] != 0 && G[j][track[j]] < min){
k = j;
min = G[j][track[j]];
}
}
T[0][i] = k;
T[1][i] = track[k];
track[k] = 0;
// Update track array to track min cost edges
for (int j {1}; j<V; j++){
if (track[j] != 0 && G[j][k] < G[j][track[j]]){
track[j] = k;
}
}
}
PrintMST(T, G);
}
int main() {
int cost [V][V] {
{I, I, I, I, I, I, I, I},
{I, I, 25, I, I, I, 5, I},
{I, 25, I, 12, I, I, I, 10},
{I, I, 12, I, 8, I, I, I},
{I, I, I, 8, I, 16, I, 14},
{I, I, I, I, 16, I, 20, 18},
{I, 5, I, I, I, 20, I, I},
{I, I, 10, I, 14, 18, I, I},
};
int n = sizeof(cost[0])/sizeof(cost[0][0]) - 1;
PrimsMST(cost, n);
return 0;
}