MST_1584_连接所有点的最小费用_最小生成树 Minimum Spanning Tree

文章目录

  • Prim Algorithm
  • Kruskal Algorithm
  • LeetCode1584. 连接所有点的最小费用
    • 题目描述
    • Prim解法 - 这里是稠密图 用O(n^2) 解法
    • Kruskal解法
  • Reference

MST_1584_连接所有点的最小费用_最小生成树 Minimum Spanning Tree_第1张图片

Prim Algorithm

MST_1584_连接所有点的最小费用_最小生成树 Minimum Spanning Tree_第2张图片

MST_1584_连接所有点的最小费用_最小生成树 Minimum Spanning Tree_第3张图片

Kruskal Algorithm

MST_1584_连接所有点的最小费用_最小生成树 Minimum Spanning Tree_第4张图片
MST_1584_连接所有点的最小费用_最小生成树 Minimum Spanning Tree_第5张图片

LeetCode1584. 连接所有点的最小费用

题目描述

MST_1584_连接所有点的最小费用_最小生成树 Minimum Spanning Tree_第6张图片
MST_1584_连接所有点的最小费用_最小生成树 Minimum Spanning Tree_第7张图片
MST_1584_连接所有点的最小费用_最小生成树 Minimum Spanning Tree_第8张图片

Prim解法 - 这里是稠密图 用O(n^2) 解法

class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        cost, n = 0, len(points)
        vis = [0] * n
        distance = [float('inf')] * n
        distance[0] = 0
        for _ in range(n):
            node = -1
            mid_cost = float('inf')
            for i in range(n):
                if not vis[i] and distance[i] < mid_cost:
                    mid_cost = distance[i]
                    node = i 
            cost += mid_cost
            vis[node] = 1
            for j in range(n):
                if not vis[j]:
                    a = abs(points[node][0] - points[j][0])
                    b = abs(points[node][1] - points[j][1])
                    distance[j] = min(distance[j], a+b)
        return cost

Kruskal解法

class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        # if len(points) < 2: return 0
        data_dict = {
     }  # (start, end): distance
        for i in range(len(points)):
            for j in range(i+1, len(points)):
                a = abs(points[i][0] - points[j][0])
                b = abs(points[i][1] - points[j][1])
                data_dict[(i, j)] = a+b
        data = sorted(data_dict.items(), key=lambda item: item[1])
        tree = [_ for _ in range(len(points))]

        def find_root(x):
            if tree[x] == x: return x
            else: return find_root(tree[x])

        res = 0
        for one, cost in data:
            a, b = one
            a_root = find_root(a)
            b_root = find_root(b)
            if a_root != b_root:
                res += cost
                tree[a_root] = b_root
        return res

Reference

https://www.bilibili.com/video/av84820276/

你可能感兴趣的:(LeetCode题解,python,leetcode,最小生成树)