Min Cost to Connect All Points
Connect every point with minimum total Manhattan edge cost.
Open on LeetCode ↗Intuition
Choosing each point's cheapest neighbor can create disconnected clusters or cycles. Treat points as vertices of a complete weighted graph, where Manhattan distance is the edge weight. Connecting all vertices for minimum total weight is exactly a minimum spanning tree. Prim's algorithm grows one connected component by repeatedly taking its cheapest crossing edge.
Whenever all locations must be connected and edge costs are additive, consider a minimum spanning tree. A dense implicit graph often favors Prim's algorithm because edges can be generated as vertices enter the tree.
Approach
Begin Prim's frontier at the first point
Put (0, 0) in a min-heap: point zero can enter the tree for no cost. Track visited points so a vertex contributes to the total only on its first removal.
Accept the cheapest edge crossing into an unseen point
Pop the minimum pair, skip it if its endpoint is already visited, otherwise add its cost and mark the point. The cut property guarantees this cheapest frontier edge is safe for an MST.
Expose Manhattan edges from each accepted point
Compute distances from the newly visited point to every unvisited point and push them into the heap. Stop after n vertices have joined; stale alternatives may remain in the heap but cannot change the tree.
Solution
Common pitfalls
Adding costs for stale heap entries
cost, point = heappop(heap) total += cost
cost, point = heappop(heap)
if point in visited:
continue
total += costMultiple candidate edges can lead to the same vertex, but an MST accepts it only once.
Using Euclidean distance
distance = sqrt(dx * dx + dy * dy)
distance = abs(dx) + abs(dy)
The problem explicitly assigns Manhattan edge costs.
Stopping when the heap first empties incorrectly
while heap and len(visited) < n - 1:
while heap and len(visited) < n:
All n vertices, including the starting point, must be accepted.
Edge cases
The initial zero-cost entry visits it and the result remains zero.
The visited check accepts only the cheapest first entry and discards stale ones.
Absolute coordinate differences compute Manhattan distance without special handling.