Min Cost to Connect All Points Problem
Description
LeetCode Problem 1584.
You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [x_i, y_i].
The cost of connecting two points [x_i, y_i] and [x_j, y_j] is the manhattan distance between them: |x_i - x_j| + |y_i - y_j|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:

Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:

We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
Example 2:
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Constraints:
1 <= points.length <= 1000-10^6 <= x_i, y_i <= 10^6- All pairs
(x_i, y_i)are distinct.
Solution
Approach: Prim's Algorithm on the Complete Graph
"Exactly one simple path between any two points" means the chosen connections form a spanning tree, so we want the minimum spanning tree of the complete graph whose edge weights are Manhattan distances.
With up to 1000 points the graph has about 500,000 edges, so it is dense. The simple O(n2) version of Prim's algorithm fits it well and needs no heap and no edge list:
- Keep
dist[j], the cheapest edge from pointjto the tree built so far. Start withdist[0] = 0and everything else infinite. - Repeat
ntimes: pick the pointioutside the tree with the smallestdist[i], add it to the tree and adddist[i]to the answer. Then, for every pointjstill outside, updatedist[j]with the distance fromjtoi.
Distances are computed on the fly, so there is no n x n matrix to store.
Complexity: O(n2) time and O(n) extra space.
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n = len(points)
dist = [float("inf")] * n # cheapest edge from each point to the tree so far
in_tree = [False] * n
dist[0] = 0
ans = 0
for _ in range(n):
# add the closest point that is not in the tree yet
i = -1
for j in range(n):
if not in_tree[j] and (i == -1 or dist[j] < dist[i]):
i = j
in_tree[i] = True
ans += dist[i]
x1, y1 = points[i]
for j in range(n):
if not in_tree[j]:
d = abs(x1 - points[j][0]) + abs(y1 - points[j][1])
if d < dist[j]:
dist[j] = d
return ans