-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1584.连接所有点的最小费用.java
66 lines (58 loc) · 1.65 KB
/
1584.连接所有点的最小费用.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
/*
* @lc app=leetcode.cn id=1584 lang=java
*
* [1584] 连接所有点的最小费用
*/
// @lc code=start
class Solution {
static class Edge implements Comparable<Edge>{
int from, to, cost;
Edge(int from, int to, int cast){
this.from = from;
this.to = to;
this.cost = cast;
}
@Override
public int compareTo(Edge e){
return cost - e.cost;
}
}
Set<Integer> set = new HashSet<>();
Edge[][] edges;
PriorityQueue<Edge> edgesInOrder = new PriorityQueue<>();
int n;
int ans = 0;
public int minCostConnectPoints(int[][] points) {
n = points.length;
edges = new Edge[n][n];
for(int i = 0;i < n;++i){
for(int j = i + 1;j < n;++j){
int dx = Math.abs(points[i][0] - points[j][0]);
int dy = Math.abs(points[i][1] - points[j][1]);
edges[j][i] = new Edge(j, i, dx + dy);
edges[i][j] = new Edge(i, j, dx + dy);
}
}
set.add(0);
for(int i = 1;i < n;++i){
edgesInOrder.add(edges[0][i]);
}
while(set.size() < n){
Edge edge = edgesInOrder.poll();
if(!set.contains(edge.to)){
ans += edge.cost;
set.add(edge.to);
for(int i = 0;i < n;++i){
if(i == edge.to) continue;
edgesInOrder.add(edges[edge.to][i]);
}
}
}
return ans;
}
}
// @lc code=end