27. Min Cost to Connect All Points

You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].

The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.

Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.

Example 1:

Example 1:
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20

Example 2:

Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18

Example 3:

Input: points = [[0,0],[1,1],[1,0],[-1,1]]
Output: 4

Example 4:

Input: points = [[-1000000,-1000000],[1000000,1000000]]
Output: 4000000

Example 5:

Input: points = [[0,0]]
Output: 0

Solution: (MST)

Approach:- Connect all points and find mst

class Solution
{
public:
    void findMst(vector<pair<int, int>> v[], vector<int> &key, vector<bool> &vs)
    {

        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

        pq.push({0, 0});
        key[0] = 0;

        while (!pq.empty())
        {
            int node = pq.top().second;
            int weight = pq.top().first;
            vs[node] = true;
            pq.pop();

            for (int i = 0; i < v[node].size(); i++)
            {
                if (!vs[v[node][i].first] && v[node][i].second < key[v[node][i].first])
                {
                    pq.push({v[node][i].second, v[node][i].first});
                    key[v[node][i].first] = v[node][i].second;
                }
            }
        }
    }

    int minCostConnectPoints(vector<vector<int>> &points)
    {

        int n = points.size();
        vector<pair<int, int>> v[n];

        for (int i = 0; i < n; i++)
        {

            for (int j = i + 1; j < n; j++)
            {

                int dist = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]);
                v[i].push_back({j, dist});
                v[j].push_back({i, dist});
            }
        }

        vector<int> key(n, INT_MAX);
        vector<bool> vs(n, false);

        findMst(v, key, vs);

        int s = 0;
        for (int i = 0; i < n; i++)
        {
            s += key[i];
        }

        return s;
    }
};

Last updated