Leetcode 1584. 连接所有点的最小费用

1.题目基本信息

1.1.题目描述

给你一个points 数组,表示 2D 平面上的一些点,其中 points[i] = [x_i, y_i] 。

连接点 [x_i, y_i] 和点 [x_j, y_j] 的费用为它们之间的 曼哈顿距离 :|x_i -- x_j| + |y_i -- y_j| ,其中 |val| 表示 val 的绝对值。

请你返回将所有点连接的最小总费用。只有任意两点之间 有且仅有 一条简单路径时,才认为所有点都已连接。

1.2.题目地址

https://leetcode.cn/problems/min-cost-to-connect-all-points/description/

2.解题方法

2.1.解题思路

最小生成树+Prim算法/Kruskal算法

2.2.解题步骤

Kruskal算法

  • 第一步,构建边的堆
  • 第二步,构建并查集并初始化节点
  • 第三步,从堆中弹出(节点数-1)条非内联边加到并查集中

Prim算法

  • 第一步,构建有向图
  • 第二步,Prim算法构建最小生成树并获取其权值和

3.解题代码

Python代码(Kruskal算法)(附并查集模板)

python 复制代码
# # ==> 并查集模板(附优化)
class UnionFind():
    def __init__(self):
        self.roots={}
        self.setCnt=0   # 连通分量的个数
        # Union优化:存储根节点主导的集合的总节点数
        self.rootSizes={}
    
    def add(self,x):
        if x not in self.roots:
            self.roots[x]=x
            self.rootSizes[x]=1
            self.setCnt+=1
    
    def find(self,x):
        root=x
        while root != self.roots[root]:
            root=self.roots[root]
        # 优化:压缩路径
        while x!=root:
            temp=self.roots[x]
            self.roots[x]=root
            x=temp
        return root
    
    def union(self,x,y):
        rootx,rooty=self.find(x),self.find(y)
        if rootx!=rooty:
            # 优化:小树合并到大树上
            if self.rootSizes[rootx]<self.rootSizes[rooty]:
                self.roots[rootx]=rooty
                self.rootSizes[rooty]+=self.rootSizes[rootx]
            else:
                self.roots[rooty]=rootx
                self.rootSizes[rootx]+=self.rootSizes[rooty]
            self.setCnt-=1

import heapq
class Solution:
    # Kruskal算法
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        pcnt=len(points)
        # 构建边的堆
        edgesHeap=[]
        for i in range(pcnt):
            for j in range(i+1,pcnt):
                dist=abs(points[i][0]-points[j][0])+abs(points[i][1]-points[j][1])
                heapq.heappush(edgesHeap,(dist,i,j))
        # 构建并查集并初始化节点
        uf=UnionFind()
        for i in range(pcnt):
            uf.add(i)
        # 从堆中弹出(节点数-1)条非内联边加到并查集中
        addedEdgesCnt=0
        minTotalWeight=0
        while addedEdgesCnt<pcnt-1:
            weight,node1,node2=heapq.heappop(edgesHeap)
            if uf.find(node1)!=uf.find(node2):
                uf.union(node1,node2)
                minTotalWeight+=weight
                addedEdgesCnt+=1
        return minTotalWeight

Python代码(附Prim算法模板)

python 复制代码
import heapq
from typing import Dict,List
# ==> Prim算法模板:用于计算无向图的最小生成树及最小权值和
# graph:无向图的邻接表;item项例子:{节点:[[相邻边的权值,相邻边对面的节点],...],...}
# return:minWeightsSum为最小生成树的权值和;treeEdges为一个合法的最小生成树的边的列表(列表项:[节点,对面节点,两点之间的边的权值]);visited为最小生成树的节点,可以用来判断图中是否存在最小生成树
def primMinSpanningTree(graph:List[List[List]]):
    minWeightsSum,treeEdges=0,[]
    firstNode=0
    # 记录已经加入最小生成树的节点
    visited=set([firstNode])
    # 选择从firstNode开始,相邻的边加到堆中
    neighEdgesHeap=[item+[firstNode] for item in graph[firstNode]]
    heapq.heapify(neighEdgesHeap)
    while neighEdgesHeap:
        weight,node,startNode=heapq.heappop(neighEdgesHeap) # node2为node的weight权值对应的边的对面的节点
        if node in visited:    # 这个地方必须进行判断,否则会造成重复添加已访问节点,造成最小权值和偏大(因为前面遍历的节点可能将未遍历的共同相邻节点重复添加到堆中)
            continue
        minWeightsSum+=weight
        treeEdges.append([startNode,node,weight])
        visited.add(node)
        # 遍历新访问的节点的边,加入堆中
        for nextWeight,nextNode in graph[node]:
            if nextNode not in visited:
                heapq.heappush(neighEdgesHeap,[nextWeight,nextNode,node])
    return minWeightsSum,treeEdges,visited


class Solution:
    # Prim算法
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        pcnt=len(points)
        # 第一步,构建有向图
        graph=[[] for i in range(pcnt)]
        for i in range(pcnt):
            for j in range(i+1,pcnt):
                dist=abs(points[i][0]-points[j][0])+abs(points[i][1]-points[j][1])
                graph[i].append([dist,j])
                graph[j].append([dist,i])
        # print(graph)
        # 第二步,Prim算法构建最小生成树并获取其权值和
        minTotalDist,_,_=primMinSpanningTree(graph)
        # print(minTotalDist)
        return minTotalDist

4.执行结果

相关推荐
Wilber的技术分享1 小时前
【机器学习实战笔记 14】集成学习:XGBoost算法(一) 原理简介与快速应用
人工智能·笔记·算法·随机森林·机器学习·集成学习·xgboost
巴里巴气1 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19891 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
JavaEdge在掘金1 小时前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python
Tanecious.1 小时前
LeetCode 876. 链表的中间结点
算法·leetcode·链表
ansurfen1 小时前
我的第一个AI项目:从零搭建RAG知识库的踩坑之旅
python·llm
前端付豪1 小时前
20、用 Python + API 打造终端天气预报工具(支持城市查询、天气图标、美化输出🧊
后端·python
Wo3Shi4七1 小时前
哈希冲突
数据结构·算法·go
前端付豪1 小时前
19、用 Python + OpenAI 构建一个命令行 AI 问答助手
后端·python
呆呆的小鳄鱼1 小时前
cin,cin.get()等异同点[面试题系列]
java·算法·面试