Prim算法实现

博客围绕图和Prim算法展开,虽原文未给出具体内容,但推测会涉及图的相关概念及Prim算法的原理、应用等信息技术领域知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
# @Time    : 2019/5/25 12:31
# @Author  : WHS
# @FileName: text.py
# @Software: PyCharm
# @Python Version:3.6.0
from collections import defaultdict
from heapq import heapify,heappop,heappush
#heappush(入堆)、heappop(出堆)、heapify(创建堆)
def Prim(nodes,edges):
    #无向图
    conn = defaultdict(list)
    for n1,n2,c in edges:
        conn[n1].append((c,n1,n2))
        conn[n2].append((c,n2,n1))
    #print(conn)
    mst = []
    used = set(nodes[0])  #已访问过的顶点
    usable_edges = conn[nodes[0]]
    heapify(usable_edges)  #建堆
    while usable_edges:
        cost, n1, n2 = heappop(usable_edges)  #权重 顶点  找出权重最小的边
        if n2 not in used:  #顶点n2没有被访问
            used.add(n2)  #将n2加入到已访问集合
            mst.append((n1, n2, cost))  #存储过程

            for e in conn[n2]:  #遍历顶点n2能到达的顶点
                if e[2] not in used:  #如果顶点n2能到达的顶点不在已访问顶点集合中,则加入其能到达的边
                    heappush(usable_edges, e)
    return mst

nodes = list("ABCDEFG")
edges = [ ("A", "B", 7), ("A", "D", 5),
               ("B", "C", 8), ("B", "D", 9),
               ("B", "E", 7), ("C", "E", 5),
               ("D", "E", 15), ("D", "F", 6),
               ("E", "F", 8), ("E", "G", 9),
               ("F", "G", 11)]

print(Prim(nodes,edges))

原文

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值