-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrim'sAlgo.cpp
37 lines (33 loc) · 928 Bytes
/
Prim'sAlgo.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
class Solution
{
public:
//Function to find sum of weights of edges of the Minimum Spanning Tree.
int spanningTree(int V, vector<vector<int>> adj[])
{
// code here
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>q;
vector<int>visited(V,0);
int sum=0;
// {Wt,Node}
q.push({0,0});
while(!q.empty()){
auto it=q.top();
q.pop();
int wt=it.first;
int node=it.second;
if(visited[node]==1){
continue;
}
visited[node]=1;
sum+=wt;
for(auto it:adj[node]){
int adjNode=it[0];
int edW=it[1];
if(!visited[adjNode]){
q.push({edW,adjNode});
}
}
}
return sum;
}
};