Minimum Spanning Trees (MST)

1584. Min Cost to Connect All Points

class UnionFind {
    vector<int> root;

public:
    UnionFind(int n) {
        root.resize(n);
        iota(root.begin(), root.end(), 0);
    }

    int find(int p) {
        while (p != root[p]) {
            root[p] = root[root[p]]; // Path compression
            p = root[p];
        }
        return p;
    }

    void connect(int a, int b) {
        int rootA = find(a), rootB = find(b);
        if (rootA != rootB) {
            root[rootA] = rootB;
        }
    }
};

class Solution {
private:
    vector<array<int, 3>> edges;

    int getDist(int i, int j, const vector<vector<int>>& points) {
        return abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]);
    }

public:
    int minCostConnectPoints(vector<vector<int>>& points) {
        int n = points.size();
        if (n == 1) return 0;

        // Generate all unique edges (i, j, cost)
        for (int i = 0; i < n - 1; ++i) {
            for (int j = i + 1; j < n; ++j) {
                edges.push_back({i, j, getDist(i, j, points)});
            }
        }

        // Sort edges by cost
        sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {
            return a[2] < b[2];
        });

        UnionFind uf(n);
        int cost = 0, connected = 0;

        // Kruskal's algorithm
        for (const auto& e : edges) {
            int a = e[0], b = e[1], w = e[2];
            if (uf.find(a) != uf.find(b)) {
                uf.connect(a, b);
                cost += w;
                connected++;
                if (connected == n - 1) return cost;
            }
        }

        return -1; // Should not happen for valid input
    }
};

1135. Connecting Cities With Minimum Cost

1168. Optimize Water Distribution in a Village

Last updated

Was this helpful?