LeetCode323 Number of Connected Components in an Undirected Graph
Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]]
0 3
| |
1 --- 2 4
Output: 2
it is quite easy to understtandi this problem.
now, how to solve it?
if you really think about this, it is a classic-classic union find problem
just union and find. recite it like presort/postorder/inorder.levelirder
Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]]
class Solution {
public int countComponents(int n, int[][] edges) {
int[] roots = new int[n];
for (int i = 0; i < n; i++) { //initialize every node as its father node
roots[i] = i;
}
for (int[] e:edges) { //for every edges
int root1 = find(roots, e[0]);
int root2 = find(roots, e[1]);
if (root1 != root2) {
roots[root1] = root2; //attach root1 to root2
n--;
}
}
return n;
}
private int find(int[] roots, int id) {
int oid = id;
while (roots[id] != id) {
id = roots[id]; //go up to previous level
}//and the id will final locates at where the untimate root of oid
roots[oid] = id; //and finally, the id node is directed to the aultimate root
return id;
}
}

浙公网安备 33010602011771号