class Solution {
public:
vector<int>fathers;
// vector<int>rank;
int rank[10000];
int find(int i){
while(fathers[i]!=i) {fathers[i]=fathers[fathers[i]]; i=fathers[i];}
return i;
}
bool isConnected(int i,int j){
return find(i)==find(j);
}
void uni (int i,int j){
int iRoot=find(i);
int jRoot=find(j);
if(iRoot==jRoot)
return ;
// fathers[iRoot]=jRoot;
if(rank[iRoot]<rank[jRoot])
fathers[iRoot]=jRoot;
else if(rank[iRoot]>rank[jRoot])
fathers[jRoot]=iRoot;
else{
fathers[iRoot]=jRoot;
rank[jRoot]+=1;
}
}
int findCircleNum(vector<vector<int>>& M) {
int n=M.size();
if(n==0){
return 0;
}
for(int i=0;i<n;i++){
fathers.push_back(i);
rank[i]=1;
}
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++)
if(M[i][j]){
uni(i,j);
}
}
int count=0;
for(int i=0;i<n;i++){
if(fathers[i]==i)
count++;
}
return count;
}
};
547. 朋友圈(并查集系列)
最新推荐文章于 2021-03-02 05:58:28 发布