Minimum Cost to Connect All Points
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Graphs.
Minimum Cost to Connect All Points
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|.Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Visual Representation
Points: [[0,0],[2,2],[3,10],[5,2],[7,0]]
(3,10)
|
|
(0,0)-(2,2)-(5,2)-(7,0)
Min Cost to connect all points: 20Examples
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Points are connected with total manhattan distance 20.
Approach 1
Level II: Intermediate (Kruskal's Algorithm)
Intuition
Kruskal's algorithm works by sorting all potential edges by weight and adding them one by one if they don't form a cycle (using Union-Find).
Thought Process
- Generate all possible edges with their Manhattan distances.
- Sort edges by weight.
- Use Union-Find to process edges.
- Add edge to MST if endpoints are in different components.
- Stop when edges are added.
Why it's Level II
It's very intuitive but slightly slower for dense graphs () compared to Prim's .
⏱ O(N^2 log N) - Due to sorting O(N^2) edges.💾 O(N^2) - To store all possible edges.
Detailed Dry Run
Points: [0,0], [2,2], [7,0]
- Edges: (0,1):4, (1,2):7, (0,2):7.
- Sort: [(0,1):4, (1,2):7, (0,2):7]
- Add (0,1): Cost=4. OK.
- Add (1,2): Cost=4+7=11. OK. Result: 11
Approach 2
Level III: Optimal (Prim's Algorithm)
Intuition
For a dense graph (where every point connects to every other point), Prim's algorithm with a simple array is more efficient than Kruskal's or Prim's with a heap.
Thought Process
- Maintain a
minDistarray whereminDist[i]is the shortest distance from the current MST to pointi. - Start with point 0,
minDist[0] = 0. - In each of iterations:
- Find the unvisited point
uwith the smallestminDist. - Add
minDist[u]to total cost. - Mark
uas visited. - For every unvisited point
v, updateminDist[v] = min(minDist[v], dist(u, v)).
- Find the unvisited point
Pattern: Prim's on Dense Graph
⏱ O(N^2) - No priority queue needed for dense graphs.💾 O(N) - To store minDist and visited status.
Detailed Dry Run
Points: [0,0], [2,2], [3,10]
- Start with node 0.
- Node 0 to 1: dist 4. Node 0 to 2: dist 13.
- Choose node 1 (min dist 4). Total = 4.
- Node 1 to 2: dist 9. 9 < 13. Update minDist[2] = 9.
- Choose node 2. Total = 4 + 9 = 13. Result: 13
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.