Introduction
Min Cost to Connect All Points is a classic Minimum Spanning Tree problem.
You are given:
- Points on a 2D plane
- Cost between two points = Manhattan Distance
Goal:
Connect all points with minimum total cost.
Example
Input
points =
[[0,0], [2,2], [3,10], [5,2], [7,0]]
Output
20 Key Observation
Every point can connect to every other point.
The cost of an edge is:
|x1 - x2| + |y1 - y2| This becomes a Minimum Spanning Tree problem.
Algorithm
- Start from any point.
- Add reachable points into min heap.
- Select minimum cost edge.
- Add unvisited point into MST.
- Continue until all points are connected.
Dry Run
Start Point
(0,0)
Add Closest Point
Cost = 4
Continue Expanding MST
4 + 3 + 4 + 9
Answer
20Approach : Prim's Algorithm
Treat every point as a graph node.
Use Manhattan Distance as edge weight.
Prim's Algorithm efficiently builds the MST while minimizing total cost.