class Solution {
public int findCircleNum(int[][] M) {
int[] father=new int[M.length];
for(int i = 0; i < M.length; ++i)
father[i] = i;
int cnt = 0;
for(int i = 0; i < M.length; ++i){
for(int j = i+1 ; j < M[0].length; ++j){
if(M[i][j] == 1) merge(i, j, father);
}
}
for(int i = 0; i < M.length; ++i){
if(father[i] == i) cnt++;
}
return cnt;
}
int find(int x, int[] father){
while(father[x] != x){
x = father[x];
}
return x;
}
void merge(int a, int b, int[] father){
int x = find(a,father), y = find(b,father);
if(x != y)
father[x] = y;
}
}
或者
class Solution {
public int[] father;
public int findCircleNum(int[][] M) {
father=new int[M.length];
for(int i = 0; i < M.length; ++i)
father[i] = i;
int cnt = 0;
for(int i = 0; i < M.length; ++i){
for(int j = i+1 ; j < M[0].length; ++j){
if(M[i][j] == 1) merge(i, j);
}
}
for(int i = 0; i < M.length; ++i){
if(father[i] == i) cnt++;
}
return cnt;
}
int find(int x){
while(father[x] != x){
x = father[x];
}
return x;
}
void merge(int a, int b){
int x = find(a), y = find(b);
if(x != y)
father[x] = y;
}
}
或者DFS
class Solution {
public int findCircleNum(int[][] M) {
int len=M.length;
int num=0;
boolean[] visited=new boolean[len];
for(int i=0;i<len;i++){
if(!visited[i]){
dfs(M,i,visited);
num++;
}
}
return num;
}
public void dfs(int[][] M,int i,boolean[] visited){
visited[i]=true;
for(int j=0;j<M[0].length;j++){
if(M[i][j]==1 && !visited[j]){
dfs(M,j,visited);
}
}
}
}