Min Cost to Connect All Points

Medium

Topics
GraphMinimum Spanning TreeHeap

You are given points where points[i] = [x, y]. The cost to connect two points is their Manhattan distance. Return the minimum cost to connect all points so every pair is reachable. (Input rows are the points.)

Example 1

434901234
Node i is point [0, 0]-style coordinate points[i], and every pair is joinable at its Manhattan distance. The answer is the cheapest set of 4 edges that still connects everything — a minimum spanning tree, total 20. Edge labels are those distances.
Input is a list of [x, y] points; the figure shows the chosen spanning tree with its edge weights.
Input:  points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20

Example 2

126012
Input:  points = [[3,12],[-2,5],[-4,1]]
Output: 18

Constraints

  • 1 <= points.length <= 1000
  • -10^6 <= xi, yi <= 10^6
Editorial — intuition, approach, complexity and pitfalls

Intuition

This is a minimum spanning tree on a complete graph where edge weights are Manhattan distances. Prim’s algorithm grows the tree by repeatedly adding the cheapest edge to a new point.

Approach

  1. Start from any point; track the min distance from the growing tree to each outside point.
  2. Repeatedly pick the closest outside point, add its distance to the total, and mark it in the tree.
  3. Update the distances of remaining points against the newly added one.

Dry Run

points [0,0] [2,2] [3,10] [5,2] [7,0], Manhattan distance
Prim's: dist[v] is the cheapest known edge from the tree so far to v, not a path
length. Grow the tree one node at a time, always taking the cheapest fringe.
  pick 0  cost 0   total  0   dist becomes [0, 4, 13, 7, 7]
  pick 1  cost 4   total  4   improves dist[2] 13->9, dist[3] 7->3
  pick 3  cost 3   total  7   improves dist[4] 7->4
  pick 4  cost 4   total 11   improves nothing
  pick 2  cost 9   total 20   improves nothing
answer 20
Watch dist[3] fall from 7 to 3 when node 1 joins. Each new tree node can only
make the fringe cheaper, never more expensive, which is why relaxing with
`if d < dist[v]` is required -- assign unconditionally and a cheaper edge found
earlier is overwritten by whatever the newest node happens to cost, giving 25
instead of 20.
The `not in_mst[i]` filter in the SELECTION loop is what makes this Prim's rather
than an infinite shuffle. Without it the cheapest node is always one already in
the tree, at dist 0, so the total comes out 0 for every input.
The same-looking filter in the RELAXATION loop is not load-bearing, which is worth
knowing before hunting a bug: a node already in the tree can have its dist
lowered harmlessly, because it will never be selected again. Removing that one
changes no answer across 3000 random point sets.
No edge list is built. All n^2 distances are computed on demand, which is the
right call on a complete geometric graph -- materialising 10^6 edges to sort them
would cost more than this O(n^2) scan.

Complexity

  • Time — O(n^2): dense Prim’s over all point pairs.
  • Space — O(n): the distance and in-tree arrays.

Common Pitfalls

  • Relax with if d < dist[v]. Assigning dist[v] = d unconditionally overwrites a cheaper edge found earlier with whatever the newest tree node happens to cost, and the total comes out 25 instead of 20.
  • The not in_mst[i] filter is what makes this Prim's rather than a loop. Without it the nearest node is always one already in the tree at distance 0, so the total is 0 for every input.
  • The identical-looking filter in the relaxation loop is not load-bearing, which is worth knowing before you hunt for a bug there. A node already in the tree can have its dist lowered harmlessly, since it will never be selected again; removing that filter changes no answer across 3000 random point sets.

Full Solution — all languages

class Solution:
    def minCostConnectPoints(self, grid):
        pts=grid; n=len(pts)
        if n<=1: return 0
        in_mst=[False]*n; dist=[float('inf')]*n; dist[0]=0; total=0
        for _ in range(n):
            u=-1
            for i in range(n):
                if not in_mst[i] and (u==-1 or dist[i]<dist[u]): u=i
            in_mst[u]=True; total+=dist[u]
            for v in range(n):
                if not in_mst[v]:
                    d=abs(pts[u][0]-pts[v][0])+abs(pts[u][1]-pts[v][1])
                    if d<dist[v]: dist[v]=d
        return total
SensAI
Beta
Tap the mic to stop voice mode