Skip to content

Commit 5f1eba4

Browse files
authored
Create Solution.cpp
1 parent d06be43 commit 5f1eba4

File tree

1 file changed

+52
-0
lines changed
  • 23 - Graph Data Structure Problems/14 - Minimum Spanning Tree | Prim's Algorithm

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Solution
2+
{
3+
public:
4+
// Function to find the sum of weights of edges of the Minimum Spanning Tree (MST)
5+
int spanningTree(int V, vector<vector<int>> adj[])
6+
{
7+
// Create a vector to track if a node is included in the MST (initialized to false)
8+
vector<int> MST(V, false);
9+
10+
// Create a priority queue (min-heap) to store edges,
11+
// where each element is a pair: (weight, vertex)
12+
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
13+
14+
// Variable to store the total weight of the MST
15+
int totalWeight = 0;
16+
17+
// Push the first node (0th vertex) with weight 0 into the priority queue to start from
18+
pq.push({0, 0});
19+
20+
// While there are still nodes to be processed
21+
while (!pq.empty()) {
22+
// Get the edge with the minimum weight (top of the priority queue)
23+
pair<int, int> top = pq.top();
24+
pq.pop();
25+
26+
// Extract the weight and node from the pair
27+
int weight = top.first;
28+
int node = top.second;
29+
30+
// If the node is already included in MST, skip it
31+
if (MST[node]) continue;
32+
33+
// Mark the current node as included in the MST
34+
MST[node] = true;
35+
36+
// Add the weight of the current edge to the total MST weight
37+
totalWeight += weight;
38+
39+
// Explore all adjacent nodes (neighbors) of the current node
40+
for (auto &edge : adj[node]) {
41+
int vertex = edge[0]; // Get the adjacent vertex
42+
int vertexWeight = edge[1]; // Get the weight of the edge to the adjacent vertex
43+
44+
// If the adjacent vertex is not already in the MST, add it to the priority queue
45+
if (!MST[vertex]) pq.push({vertexWeight, vertex});
46+
}
47+
}
48+
49+
// Return the total weight of the Minimum Spanning Tree
50+
return totalWeight;
51+
}
52+
};

0 commit comments

Comments
 (0)