MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / ConnectTheDots

Class ConnectTheDots

java/Graphs/ConnectTheDots.java:47–82  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

45}
46
47public 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected