解法一:DFS
class Solution {
public:
void helper(vector<vector<int>>& M, vector<bool>& visited, int i){
for(int j=0;j<M.size();j++){
if(M[i][j]==1 && !visited[j]){
visited[j] = true;
helper(M, visited, j);
}
}
}
int findCircleNum(vector<vector<int>>& M) {
int n = M.size();
vector<bool> visited(n, false);
int res = 0;
for(int i=0;i<n;i++){
if(!visited[i]){
visited[i]=true;
helper(M, visited, i);
res++;
}
}
return res;
}
};
解法二: BFS
class Solution {
public:
int findCircleNum(vector<vector<int>>& M) {
int n = M.size();
vector<bool> visited(n, false);
queue<int> t;
int res = 0;
for(int i=0;i<n;i++){
if(!visited[i]){
t.push(i);
while(!t.empty()){
int cur = t.front(); t.pop();
visited[cur] =true;
for(int j=0;j<n;j++){
if(M[cur][j]==1 && !visited[j]){
t.push(j);
}
}
}
res++;
}
}
return res;
}
};
解法三:Union Find
class Solution {
public:
int findCircleNum(vector<vector<int>>& M) {
int n = M.size(), res = n;
vector<int> root(n);
for(int i=0;i<n;i++) root[i]=i;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(M[i][j] == 1){
int p1 = getroot(root,i);
int p2 = getroot(root,j);
if(p1!=p2){
res--;
root[p2] = p1;
}
}
}
}
return res;
}
int getroot(vector<int>& root, int x){
while(x!=root[x]){
x = root[x];
root[x] = root[root[x]];
}
return x;
}
};