[LeetCode] Min Cost to Connect All Points

1584. 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.

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
class Solution {
vector<int> g;
int getDistance(vector<int>& p1, vector<int>& p2) {
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]);
}
int find(int n) {
return g[n] == n ? n : g[n] = find(g[n]);
}
void uni(int a, int b) {
int pa = find(a), pb = find(b);
g[pa] = g[pb] = min(pa,pb);
}
public:
int minCostConnectPoints(vector<vector<int>>& points) {
int cost = 0, n = points.size();
priority_queue<array<int,3>,vector<array<int,3>>, greater<array<int,3>>> pq;
g = vector<int>(n);

for(int i = 0; i < points.size(); i++) {
g[i] = i;
for(int j = i + 1; j < points.size(); j++) {
pq.push({getDistance(points[i], points[j]), i, j});
}
}

while(!pq.empty()) {
auto [c, f, t] = pq.top(); pq.pop();
if(find(f) == find(t)) continue;
cost += c;
uni(f,t);
}
return cost;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/08/PS/LeetCode/min-cost-to-connect-all-points/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.