一、题目
二、思路
最小生成树
class Solution {
public int minCostConnectPoints(int[][] points) {
int n = points.length;
UnionFind uf = new UnionFind(n);
//边集数组
List<Edge> edges = new ArrayList<Edge>();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
edges.add(new Edge(dist(points, i, j), i, j));
}
}
//边集数组按照曼哈顿距离排序
Collections.sort(edges, new Comparator<Edge>() {
public int compare(Edge edge1, Edge edge2) {
return edge1.len - edge2.len;
}
});
int result = 0, num = 1;
for (Edge edge : edges) {
int len = edge.len;
int x = edge.x;
int y = edge.y;
if (!uf.isConnect(x, y)) {
result += len;
num++;
uf.union(x,y);
if (num == n) {
break;
}
}
}
return result ;
}
public int dist(int[][] points, int x, int y) {
return Math.abs(points[x][0] - points[y][0]) + Math.abs(points[x][1] - points[y][1]);
}
}
//并查集
class UnionFind{
int[] parents;
UnionFind(int size){
this.parents = new int[size];
//并查集数组初始化
for(int i = 0; i < size; i++){
parents[i] = i;
}
}
public int find(int x){
int r = x;
while(parents[r] != r){
r = parents[r];
}
return r;
}
public void union(int x, int y){
int fx = find(x);
int fy = find(y);
if(fx == fy){
return;
}
parents[fx] = fy;
}
public boolean isConnect(int x, int y){
return find(x) == find(y);
}
}
class Edge {
int len, x, y;
public Edge(int len, int x, int y) {
this.len = len;
this.x = x;
this.y = y;
}
}