并查集
并查集在设定father时需要防止成环,所以需要人为规定一个序,例如大的是小的的father。
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
vector<int> fa(n);
for (int i = 0;i < n;i++) {
fa[i] = i;
}
for (int i = 0;i < n;i++) {
for (int j = i + 1;j < n;j++) {
if (isConnected[i][j]) {
int f = findFather(i, fa);
fa[min(j, f)] = max(j, f);
}
}
}
int ans = 0;
for (int i = 0;i < n;i++) {
ans += fa[i] == i;
}
return ans;
}
int findFather(int i, vector<int>& fa) {
return fa[i] == i ? i : findFather(fa[i], fa);
}
};