标签:return parent int 最小 len LeetCode Edge 1584 public
class Solution {
public class Edge{
int len;//边长度
int x;//顶点1
int y;//顶点2
public Edge(int len,int x,int y){
this.len = len;
this.x = x;
this.y = y;
}
}
public int minCostConnectPoints(int[][] points) {
int n = points.length;//顶点个数
List<Edge> edges = new ArrayList<Edge>();
UnionFind uf = new UnionFind(n);
for(int i =0;i<n-1;i++){
for(int j=i+1;j<n;j++){
int[] pointi = points[i];
int[] pointj = points[j];
int len = Math.abs(pointi[0] - pointj[0]) + Math.abs(pointi[1] - pointj[1]);
edges.add(new Edge(len,i,j));
}
}
Collections.sort(edges, new Comparator<Edge>() {
public int compare(Edge edge1, Edge edge2) {
return edge1.len - edge2.len;
}
});
int sum = 0;
int index = 0;
while(uf.count>1){
Edge edge= edges.get(index);
boolean flag = uf.Union(edge.x,edge.y);
if(flag == true)
sum += edge.len;
index+=1;
}
return sum;
}
public class UnionFind{
int[] parent;
int count;
public int getCount(){
return count;
}
public UnionFind(int n){
parent = new int[n];
count = n;
for(int i =0;i<n;i++)
parent[i] = i;
}
public int find(int x){
if(parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}
public boolean Union(int x,int y){
int rootX = find(x);
int rootY = find(y);
if(rootX == rootY)
return false ;
parent[rootX] = rootY;
count -= 1;
return true;
}
}
}
标签:return,parent,int,最小,len,LeetCode,Edge,1584,public 来源: https://blog.csdn.net/qq_44822951/article/details/122769054
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。