https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/description/
这道题就是根据边连起来,看有几个集合。典型的并查集应用。
int[] parent;
int find(int i){
if(parent[i] == i) return i;
return parent[i] = find(parent[i]);
}
boolean union(int i,int j){
int pi = find(i);
int pj = find(j);
if(pi == pj) return false;
parent[pi] = pj;
return true;
}
public int countComponents(int n, int[][] edges) {
parent = new int[n];
for(int i=0;i<n;i++)
parent[i] = i;
int cnt = n;
for(int[] edge : edges){
if(union(edge[0],edge[1])) cnt--;
}
return cnt;
}