-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial8_Q2.cpp
More file actions
70 lines (55 loc) · 1.62 KB
/
Copy pathtutorial8_Q2.cpp
File metadata and controls
70 lines (55 loc) · 1.62 KB
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
#include <iostream>
#include <climits>
using namespace std;
const int V = 6;
void Prim(int graph[V][V], int startVertex) {
int parent[V];
for(int i = 0; i < V; i++) parent[i] = -1;
bool inVT[V];
for(int i = 0; i < V; i++) inVT[i] = false;
inVT[startVertex] = true;
for (int i = 1; i <= V - 1; i++) {
int minWeight = INT_MAX;
int v_star = -1;
int u_star = -1;
for (int v = 0; v < V; v++) {
if (inVT[v]) {
for (int u = 0; u < V; u++) {
if (!inVT[u] && graph[v][u] != 0) {
if (graph[v][u] < minWeight) {
minWeight = graph[v][u];
v_star = v;
u_star = u;
}
}
}
}
}
if (v_star != -1 && u_star != -1) {
// VT <- VT U {u*}
inVT[u_star] = true;
// ET <- ET U {e*}
parent[u_star] = v_star;
}
}
cout << "Edges composing the Minimum Spanning Tree (Prim):\n";
cout << "Edge \tWeight\n";
for (int i = 0; i < V; i++) {
if (i != startVertex && parent[i] != -1) {
cout << parent[i] << " - " << i << " \t" << graph[parent[i]][i] << "\n";
}
}
}
int main() {
int graph[V][V] = {
{0, 4, 0, 0, 0, 0},
{4, 0, 8, 0, 0, 0},
{0, 8, 0, 7, 0, 4},
{0, 0, 7, 0, 9, 14},
{0, 0, 0, 9, 0, 10},
{0, 0, 4, 14, 10, 0}
};
int startVertex = 0;
Prim(graph, startVertex);
return 0;
}