
Sponsored
Sponsored
This approach involves treating the points as nodes of a graph and the Manhattan distance between them as the edge weights. The problem translates to finding a Minimum Spanning Tree (MST), which connects all nodes with the minimum edge weight.
Kruskal's algorithm is a popular choice for this kind of problem. It works as follows:
This approach efficiently computes the minimum cost of connecting all points.
The time complexity is dominated by the sorting step and the union-find operations. Sorting takes O(E log E), where E is the number of edges. Union-Find operations are nearly constant time, resulting in an overall complexity of O(E log E). The space complexity is O(n) for the Union-Find structure and edge storage, where n is the number of points.
1import java.util.*;
2
3class Solution {
4 static class Edge implements Comparable<Edge
The Java implementation uses an inner class to represent edges with the necessary fields point1, point2, and weight. Edges are sorted by weight using Java's Collections.sort to facilitate Kruskal's algorithm. The Union-Find structure is used to ensure that connecting an edge results in adding a new connection to the resulting Minimum Spanning Tree without forming cycles, and it returns the minimum cost of connecting all points.
Another approach uses Prim's algorithm to construct the Minimum Spanning Tree (MST). Rather than sorting edges, Prim's method grows the MST one vertex at a time, starting from an arbitrary vertex and adding the minimum cost edge that expands the MST.
The steps involved are:
This approach offers a clear alternative to Kruskal's, particularly well-suited to densely connected systems.
This approach has a time complexity of O(n^2) due to nested loops over nodes, suitable for problems where n is moderately sized. Space complexity is O(n) for extra arrays managing node state and weights.
1var minCostConnectPoints = function(points) {
2 const n = points.length;
3 const minDist = new Array(n).fill(Infinity);
4 const inMST = new Array(n).fill(false);
5 minDist[0] = 0;
6 const pq = new MinPriorityQueue({ priority: x => x[0] });
7 pq.enqueue([0, 0]);
8
9 let totalCost = 0;
10
11 while (!pq.isEmpty()) {
12 const [cost, u] = pq.dequeue().element;
13 if (inMST[u]) continue;
14
15 inMST[u] = true;
16 totalCost += cost;
17
18 for (let v = 0; v < n; v++) {
19 if (!inMST[v]) {
20 const dist = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
21 if (dist < minDist[v]) {
22 minDist[v] = dist;
23 pq.enqueue([dist, v]);
24 }
25 }
26 }
27 }
28
29 return totalCost;
30};This JavaScript implementation incorporates Prim's algorithm leveraging a priority queue for optimal order selection of edges. The main loop carefully adopts the least weight option, forming a complete MST through iterative examination of potential edges and connectivity expansion to invoke the least possible edge weight.