|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.Arrays; |
| 3 | +import java.util.Collections; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +class UnionFind { |
| 7 | + int[] parent; |
| 8 | + int[] size; |
| 9 | + |
| 10 | + public UnionFind(int size) { |
| 11 | + this.parent = new int[size]; |
| 12 | + this.size = new int[size]; |
| 13 | + for (int i = 0; i < size; i++) { |
| 14 | + this.parent[i] = i; |
| 15 | + } |
| 16 | + Arrays.fill(this.size, 1); |
| 17 | + } |
| 18 | + |
| 19 | + public boolean union(int x, int y) { |
| 20 | + int repX = find(x); |
| 21 | + int repY = find(y); |
| 22 | + if (repX != repY) { |
| 23 | + if (this.size[repX] > this.size[repY]) { |
| 24 | + this.parent[repY] = repX; |
| 25 | + this.size[repX] += this.size[repY]; |
| 26 | + } |
| 27 | + else { |
| 28 | + this.parent[repX] = repY; |
| 29 | + this.size[repY] += this.size[repX]; |
| 30 | + } |
| 31 | + // Return True if both groups were merged. |
| 32 | + return true; |
| 33 | + } |
| 34 | + // Return False if the points belong to the same group. |
| 35 | + return false; |
| 36 | + } |
| 37 | + |
| 38 | + public int find(int x) { |
| 39 | + if (x == this.parent[x]) { |
| 40 | + return x; |
| 41 | + } |
| 42 | + this.parent[x] = find(this.parent[x]); |
| 43 | + return this.parent[x]; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +public class ConnectTheDots { |
| 48 | + public int connectTheDots(int[][] points) { |
| 49 | + int n = points.length; |
| 50 | + // Create and populate a list of all possible edges. |
| 51 | + List<int[]> edges = new ArrayList<>(); |
| 52 | + for (int i = 0; i < n; i++) { |
| 53 | + for (int j = i + 1; j < n; j++) { |
| 54 | + // Manhattan distance. |
| 55 | + int cost = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]); |
| 56 | + edges.add(new int[]{cost, i, j}); |
| 57 | + } |
| 58 | + } |
| 59 | + // Sort the edges by their cost in ascending order. |
| 60 | + Collections.sort(edges, (a, b) -> Integer.compare(a[0], b[0])); |
| 61 | + UnionFind uf = new UnionFind(n); |
| 62 | + int totalCost, edgesAdded; |
| 63 | + totalCost = edgesAdded = 0; |
| 64 | + // Use Kruskal's algorithm to create the MST and identify its minimum cost. |
| 65 | + for (int[] edge : edges) { |
| 66 | + int cost = edge[0]; |
| 67 | + int p1 = edge[1]; |
| 68 | + int p2 = edge[2]; |
| 69 | + // If the points are not already connected (i.e. their representatives are |
| 70 | + // not the same), connect them, and add the cost to the total cost. |
| 71 | + if (uf.union(p1, p2)) { |
| 72 | + totalCost += cost; |
| 73 | + edgesAdded++; |
| 74 | + // If n - 1 edges have been added to the MST, the MST is complete. |
| 75 | + if (edgesAdded == n - 1) { |
| 76 | + return totalCost; |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + return 0; |
| 81 | + } |
| 82 | +} |
0 commit comments