1 public class Solution { 2 private int[] parent; 3 public int countComponents(int n, int[][] edges) { 4 if (edges.length == 0) { 5 return n; 6 } 7 parent = new int[n]; 8 for (int i = 0; i < n; i++) { 9 parent[i] = i; 10 } 11 12 for (int i = 0; i < edges.length; i++) { 13 int aIndex = findParent(edges[i][0]); 14 int bIndex = findParent(edges[i][1]); 15 16 if (aIndex > bIndex) { 17 parent[aIndex] = bIndex; 18 } else if (bIndex > aIndex) { 19 parent[bIndex] = aIndex; 20 } 21 } 22 23 int result = 0; 24 for (int i = 0; i < n; i++) { 25 if (parent[i] == i) { 26 result++; 27 } 28 } 29 return result; 30 } 31 32 private int findParent(int x) { 33 while (x != parent[x]) { 34 parent[x] = parent[parent[x]]; 35 x = parent[x]; 36 } 37 return x; 38 } 39 }
时间: 2024-11-17 04:21:22