Prim算法有这一篇就够啦

点这里有详细讲解


from collections import defaultdict
from heapq import heapify, heappop, heappush
def prim(map,start):
    #最小生成树
    mst = []
    #存已连接点集合
    city = {start}
    #存待走边集合
    next = map[start]#
    #待走边排序
    heapify(next)#按距离建立小顶堆
    while next:
        #取出最小边
        distance, head, tail = heappop(next)
        #如果下个路口没走过
        if tail not in city:
            #加入已连接集合
            city.add(tail)
            #加入最小生成树
            mst.append((head, tail, distance))
            # 没走过的相邻边加入
            for e in map[tail]:
                if e[2] not in city:
                    heappush(next, e)
    if len(mst)
评论注意事项
讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!

回复(1)

代码前面能有相关的说明对新手更友好一些。

考拉开学

联系方式

微信昵称:考拉开学 联系电话:18653365468 邮箱:mail@mengyakeji.com
关于我们
关于我们
平台介绍
平台介绍
联系我们
联系我们