1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| class Solution { public int findCircleNum(int[][] M) { int[] parent = new int[M.length]; for (int i = 0; i < parent.length; i++) { parent[i] = i; }
for (int i = 0; i < M.length ; i++) { for (int j = 0; j < M.length ; j++) { if (M[i][j] == 1 && i != j){ union(parent, i, j); } } }
int count = 0; for (int i = 0; i < parent.length; i++) { if (parent[i] == i){ count++; } } return count; }
public int find(int[] parent, int i){ if (parent[i] == i){ return i; } return find(parent, parent[i]); }
public int findRoot(int[] parent, int i){ if (parent[i] != i){ parent[i] = findRoot(parent, parent[i]); } return parent[i]; }
public void union(int[] parent, int i, int j){ int xset = findRoot(parent, i); int yset = findRoot(parent, j); if (xset != yset){ parent[xset] = yset; } } }
|