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 56 57 58 59 60
| class Solution { public int removeStones(int[][] stones) { int N = stones.length; int[] parent = new int[N]; for (int i = 0; i < N; i++) { parent[i] = i; }
for (int i = 0; i < stones.length; i++) { int[] arr = stones[i]; int x = arr[0]; int y = arr[1]; for (int j = i + 1; j < stones.length; j++) { int[] arr2 = stones[j]; int x2 = arr2[0]; int y2 = arr2[1]; if (x == x2 || y == y2) { unoin(i, j, parent); } } }
int result = 0; for (int i = 0; i < parent.length; i++) { if (parent[i] == i) { int count = 0; for (int j = 0; j < parent.length; j++) { if (find(j, parent) == i) { count++; } }
if (count > 1) { result += count - 1; } } }
return result; }
public int find(int j, int[] parent) { if (j != parent[j]) { parent[j] = find(parent[j], parent); } return parent[j]; }
public void unoin(int i, int j, int[] parent) { int x = find(i, parent); int y = find(j, parent); if (x != y) { parent[x] = y; } } }
|