LeetCode-Number of Connected Components in an Undirected Graph
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
Example 1:
0 3
| |
1 --- 2 4
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], return 2.
Example 2:
0 4
| |
1 --- 2 --- 3
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]], return 1.
Note:
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Analysis:
From here: https://discuss.leetcode.com/topic/32752/easiest-2ms-java-solution
This is 1D version of Number of Islands II. For more explanations, check out this 2D Solution.
npoints =nislands =ntrees =nroots.- With each edge added, check which island is
e[0]ore[1]belonging to. - If
e[0]ande[1]are in same islands, do nothing. - Otherwise, union two islands, and reduce islands count by
1. - Bonus: path compression can reduce time by
50%.
Hope it helps!
Solution:
1 public class Solution { 2 public int countComponents(int n, int[][] edges) { 3 int[] roots = new int[n]; 4 for (int i=0;i<n;i++) roots[i] = i; 5 int num = n; 6 7 int len = edges.length; 8 for (int i=0;i<len;i++){ 9 int root1 = findRoot(roots,edges[i][0]); 10 int root2 = findRoot(roots,edges[i][1]); 11 12 if (root1!=root2){ 13 roots[root1] = root2; 14 num--; 15 } 16 } 17 18 return num; 19 } 20 21 public int findRoot(int[] roots, int node){ 22 while (roots[node]!=node){ 23 roots[node] = roots[roots[node]]; 24 node = roots[node]; 25 } 26 return node; 27 } 28 }

浙公网安备 33010602011771号