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