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.