Scribbling

LeetCode: 1584. Min Cost to Connect All Points 본문

Computer Science/Coding Test

LeetCode: 1584. Min Cost to Connect All Points

focalpoint 2021. 8. 13. 22:56
class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        
        def calc_Dist(p1, p2):
            d1 = abs(p1[0] - p2[0])
            d2 = abs(p1[1] - p2[1])
            return d1 + d2
        
        def find_parent(parent, a):
            if parent[a] == a:
                return a
            parent[a] = find_parent(parent, parent[a])
            return parent[a]
        
        def union_parent(parent, a, b):
            a = find_parent(parent, a)
            b = find_parent(parent, b)
            if a < b:
                parent[b] = a
            else:
                parent[a] = b          
        
        # (distance, pnt_idx1, pnt_idx2)
        edges = []
        for i in range(len(points)):
            for j in range(i+1, len(points)):
                pnt1 = points[i]
                pnt2 = points[j]
                edges.append((calc_Dist(pnt1, pnt2), i, j))
        edges.sort()
        
        parent = [0] * len(points)
        for i in range(len(points)):
            parent[i] = i
        
        ret = 0
        
        for edge in edges:
            cost, i, j = edge
            if find_parent(parent, i) != find_parent(parent, j):
                union_parent(parent, i, j)
                ret += cost
        
        return ret