Minimum Spanning Tree

Tags : graph, geeksforgeeks, cpp, medium

Given a weighted, undirected and connected graph of V vertices and E edges. The task is to find the sum of weights of the edges of the Minimum Spanning Tree.

Your Task: Since this is a functional problem you don’t have to worry about input, you just have to complete the function spanningTree() which takes number of vertices V and an adjacency matrix adj as input parameters and returns an integer denoting the sum of weights of the edges of the Minimum Spanning Tree. Here adj[i] contains a list of lists containing two integers where the first integer a[i][0] denotes that there is an edge between i and a[i][0] and second integer a[i][1] denotes that the distance between edge i and a[i][0] is a[i][1].

Expected Time Complexity: O(ElogV)
Expected Auxiliary Space: O(V^2)

Examples #

Example 1:

Output:
5
Explanation:
Only one Spanning Tree is possible
which has a weight of 5.

Constraints #

Solutions #

class Solution
{
    public:
	//Function to find sum of weights of edges of the Minimum Spanning Tree.
    int spanningTree(int V, vector<vector<int>> adj[]) {
        
       vector<bool> vis(V+1, false);
       priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
       q.push({0, 0});
       int sum = 0;
       while(!q.empty())  {
           auto node = q.top();
           int u = node.second;
           int w = node.first;
           q.pop();
           if(!vis[u])  {
               for(auto n:adj[u])  {
                   if(!vis[n[0]])
                       q.push({n[1], n[0]});
               }
               vis[u] = true;
               sum+=w;
           }
       }
       return sum;
   }
};