Min Cost to Connect All Points
LeetCode 1584 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Kruskal: sorted edges + union-find.
मैंने Min Cost to Connect All Points (LeetCode 1584) ऐसे हल किया — Minimum Spanning Tree पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Connecting every point as cheaply as possible is a minimum spanning tree. Kruskal's algorithm sorts all candidate edges by Manhattan distance and adds each one that connects two different components, tracked by a disjoint set.
Approach
- 1
Build every pair's Manhattan distance.
- 2
Sort edges by weight.
- 3
Union endpoints in different components and add the weight.
मैंने कैसे हल किया
Kruskal + DSUPythonO(n² log n) time
class DisjointSet:
def __init__(self,n):
self.rank = [0]*(n+1)
self.parents = [i for i in range(n+1)]
def find(self,u):
if self.parents[u]==u:
return u
self.parents[u]=self.find(self.parents[u])
return self.parents[u]
def union(self,u,v):
ulp_u,ulp_v = self.find(u),self.find(v)
if ulp_u==ulp_v:
return
if self.rank[ulp_u]<self.rank[ulp_v]:
self.parents[ulp_u]=ulp_v
elif self.rank[ulp_v]<self.rank[ulp_u]:
self.parents[ulp_v]=ulp_u
elif self.rank[ulp_v]==self.rank[ulp_u]:
self.parents[ulp_v]=ulp_u
self.rank[ulp_u]+=1
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n= len(points)
ds = DisjointSet(n)
edges = []
for i in range(n):
for j in range(i+1,n):
xi,yi = points[i]
xj,yj = points[j]
wt = abs(xi - xj) + abs(yi - yj)
edges.append([wt,i,j])
edges.sort(key=lambda x:x[0])
weight = 0
for w,u,v in edges:
if ds.find(u)!=ds.find(v):
ds.union(u,v)
weight+=w
return weight
Min Cost to Connect All Points — अक्सर पूछे जाने वाले प्रश्न
Min Cost to Connect All Points के पीछे intuition क्या है?
Connecting every point as cheaply as possible is a minimum spanning tree. Kruskal's algorithm sorts all candidate edges by Manhattan distance and adds each one that connects two different components, tracked by a disjoint set.
Min Cost to Connect All Points (LeetCode 1584) कैसे हल करें?
1. Build every pair's Manhattan distance. 2. Sort edges by weight. 3. Union endpoints in different components and add the weight.
Min Cost to Connect All Points की time और space complexity क्या है?
Time: O(n² log n)। Space: O(n²)। (Accepted approach: Kruskal + DSU।)
Min Cost to Connect All Points में आम गलतियाँ क्या हैं?
Prim's with a heap avoids storing all n² edges.