Min Cost to Connect All Points - Problem
Minimum Spanning Tree Problem: Imagine you're a city planner tasked with connecting multiple districts with roads. You have
The cost of building a road between two districts is equal to their Manhattan distance:
Input: An array of 2D coordinates representing district locations
Output: The minimum cost to connect all districts with roads
n districts represented as points on a 2D coordinate plane, where each point points[i] = [xi, yi] represents the coordinates of district i.The cost of building a road between two districts is equal to their Manhattan distance:
|xi - xj| + |yi - yj|. Your goal is to find the minimum total cost to connect all districts such that there's exactly one path between any two districts (forming a tree structure).Input: An array of 2D coordinates representing district locations
Output: The minimum cost to connect all districts with roads
Input & Output
example_1.py — Basic Triangle
$
Input:
points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
›
Output:
20
💡 Note:
Connect points to form MST: (0,0)→(7,0) cost 7, (7,0)→(5,2) cost 4, (5,2)→(2,2) cost 3, (2,2)→(3,10) cost 9. Total: 7+4+3+6=20
example_2.py — Simple Square
$
Input:
points = [[3,12],[-2,5],[-4,1]]
›
Output:
18
💡 Note:
Three points form a triangle. Cheapest connections: (-4,1)→(-2,5) cost 6, (-2,5)→(3,12) cost 12. Total: 6+12=18
example_3.py — Single Point
$
Input:
points = [[0,0]]
›
Output:
0
💡 Note:
Single point needs no connections, so cost is 0
Constraints
- 1 ≤ points.length ≤ 1000
- -106 ≤ xi, yi ≤ 106
- All pairs (xi, yi) are distinct
- Manhattan distance only - not Euclidean distance
Visualization
Tap to expand
Understanding the Visualization
1
Calculate All Distances
Find Manhattan distance between every pair of points
2
Start MST Construction
Pick any starting point and mark it as connected
3
Grow the Tree
Always add the cheapest edge connecting MST to a new point
4
Complete Connection
Continue until all points are connected with n-1 edges
Key Takeaway
🎯 Key Insight: MST problems require exactly n-1 edges to connect n points optimally. Prim's greedy approach of always choosing the cheapest available connection guarantees the minimum total cost.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code