private int[] father;
public int countComponents(int n, int[][] edges) {
Set<Integer> set = new HashSet<Integer>();
father = new int[n];
for (int i = 0; i < n; i++) {
father[i] = i;
}
for (int i = 0; i < edges.length; i++) {
union(edges[i][0], edges[i][1]);
}
for (int i = 0; i < n; i++){
set.add(find(i));
}
return set.size();
}
int find(int node) {
if (father[node] == node) {
return node;
}
father[node] = find(father[node]);
return father[node];
}
void union(int node1, int node2) {
father[find(node1)] = find(node2);
}
AC JAVA code, Union Find


you can find detailed explanation here :
https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf

@禽兽样 Not necessarily so. For example, if the components were somehow already connected (components where cycles exist), decreasing the number of components might leave you with 0 components or a negative count.