⭐Commutable Islands

Using Prim's Brute Force

#include <bits/stdc++.h>
int Solution::solve(int A, vector<vector<int> > &B) {
    // adj[u] = {(v1, w2) , (v2, w2)...}
    vector<pair<int, int>> adj[A + 1];
    for(vector<int> edgeAndWeight : B) {
        int u = edgeAndWeight[0];
        int v = edgeAndWeight[1];
        int w = edgeAndWeight[2];
        
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }
    
    vector<int> weight(A + 1, INT_MAX);
    weight[0] = weight[1] = 0;
    vector<bool> mst(A + 1);
    for(int bridgeCount = 1; bridgeCount <= A - 1; bridgeCount++
        int minWeight = INT_MAX;
        int node = -1;
        for(int i = 1; i <= A; i++)
            if(!mst[i] && weight[i] < minWeight) {
                minWeight = weight[i];
                node = i;
            }        
            
        mst[node] = true;
        
        for(pair<int, int> neighbourWithWeight: adj[node]) {
            int neighbour = neighbourWithWeight.first;
            int costToNeighbour = neighbourWithWeight.second;
            
            if(mst[neighbour] == false && costToNeighbour < weight[neighbour]) 
                weight[neighbour] = costToNeighbour;
        }
    }
    
    return accumulate(weight.begin(), weight.end(), 0);
}

Time Complexity: O(n2)O(n^2)​ for Aβˆ’1A - 1 edges and for finding minimum

Space Complexity: O(2V)+O(V)+O(V)O(2V) + O(V) +O(V) for adjacency list, weights, and MST.

Using Optimized Prim's

Using Kruskal's Algorithm

Last updated