首页 > 其他 > 详细

【LeetCode】547.朋友圈

时间:2020-03-03 09:41:12      阅读:57      评论:0      收藏:0      [点我收藏+]

题目

547. 朋友圈

代码

class Solution {
public int findCircleNum(int[][] M) {
int len = M.length;
UF uf = new UF(len);
for(int i = 0; i < len; i++){
for(int j = 0; j < len; j++){
if(M[i][j] == 1){
uf.union(i, j);
}
}
}
return uf.getcount();
}
}
class UF{
private int count;//连通分量个数
private int[] parent;
private int[] size;

public UF(int n){
this.count = n;
parent = new int[n];
size = new int[n];
for(int i = 0; i < n; i++){
parent[i] = i;
size[i] = 1;
}
}
public void union(int p, int q){
int rootP = find(p);
int rootQ = find(q);
if(rootP == rootQ){
return;
}
//P 结点大于 Q Q接在P下
if(size[rootP] > size[rootQ]){
parent[rootQ] = rootP;
size[rootQ] += size[rootP];
}else{
parent[rootP] = rootQ;
size[rootP] += size[rootQ];
}
count--;
}
public boolean isConnect(int p, int q){
int rootP = find(p);
int rootQ = find(q);
return rootP == rootQ;
}
public int find(int x){
while(parent[x] != x){
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
public int getcount(){
return count;
}
}

【LeetCode】547.朋友圈

原文:https://www.cnblogs.com/whisperbb/p/12400553.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!