#1584

Min Cost to Connect All Points

Medium Prim's MST (dense graph)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Connect all points on a plane so that every point can reach every other, where an edge costs the Manhattan distance between its points. Return the minimum total cost.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: connect all points as cheaply as possible (Manhattan distance).

Why this works: that's a minimum spanning tree. Prim's grows the tree by always adding the closest outside point.

Example: [[0,0],[2,2],[3,10],[5,2],[7,0]]

add edges 4, 3, 4, 9 → total 20

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Building all n² edges and sorting them for Kruskal — works but uses much more memory.

Solve on LeetCode ↗
Complexity
  • Time: O(n²).
  • Space: O(n).
Topic: Graphs
🎬 Episodes 74–85: video coming soon