Leetcode-1584

Min Cost to Connect All 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
35
36
37
38
39
40
41
42
#include <iostream>
#include <vector>
#include <queue>

typedef std::pair<int, int> PII;

class Solution {
    int abs(std::vector<int>& a, std::vector<int>& b) {
        return std::abs(a[0] - b[0]) + std::abs(a[1] - b[1]);
    }
    
public:
    int minCostConnectPoints(std::vector<std::vector<int>>& points) {
        int n = points.size();
        int sum = 0;
        std::vector<int> visited(n, false);
        std::priority_queue<PII, std::vector<PII>, std::greater<PII>> pq;
        pq.push({0, 0});
        
        while (!pq.empty()) {
            int w = pq.top().first;
            int u = pq.top().second;
            pq.pop();
            
            if (visited[u]) {
                continue;
            }
            visited[u] = true;
            sum += w;
            
            for (int v = 0; v < n; ++v) {
                if (visited[v]) {
                    continue;
                }
                w = abs(points[u], points[v]);
                pq.push({w, v});
            }
        }
        
        return sum;
    }
};

Leetcode-1584