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.
intminCostConnectPoints(vector<vector<int>>& points){ int size = points.size(); edges = vector<vector<vector<int>>>(size, vector<vector<int>>()); visited = vector<bool>(size, false); for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { int distance = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]); edges[i].push_back({distance, j}); edges[j].push_back({distance, i}); } }
int sum = 0; int count = 1; cut(0); visited[0] = true;
while (!pq.empty()) { auto edge = pq.top(); pq.pop(); int to = edge[1]; if (visited[to]) { continue; } int w = edge[0]; sum += w; count++; if (count == size) break; cut(to); visited[to] = true; }
return sum; }
voidcut(int node){ for (auto edge : edges[node]) { int to = edge[1]; if (!visited[to]) { int w = edge[0]; pq.push({w, to}); } } } };