用Python实现最小生成树的Prim算法

 用Prim算法求解无向连通图的最小生成树:

输入的图如下所示:

用Python实现最小生成树的Prim算法_第1张图片

期望得到的结果:

用Python实现最小生成树的Prim算法_第2张图片

输入例子如下所示:

6 10

0 1 7

0 2 4

0 3 3

0 5 7

1 3 6

1 4 5

1 5 2

2 3 8

2 4 5

3 4 1

代码如下:

VexNumber,EdgeNumber=list(map(int,input().split()))#读取顶点的个数和边的个数
EdgeList=[[float("inf")]*VexNumber for i in range(VexNumber)]#存放读入的边
for i in range(EdgeNumber):#读取每条边
    Vex1,Vex2,EdgeWeight=list(map(int,input().split()))
    EdgeList[Vex1][Vex2]=EdgeWeight
    EdgeList[Vex2][Vex1] = EdgeWeight
OuputEdge={}#存放最终的结果
RedPoint=[0]#红点集
BluePoint=[i for i in range(1,VexNumber)]#蓝点集
BluePointToRed=[0]*VexNumber#存放每个蓝点对应紫边的另一个红点
PurpleEdgeWeight=[float("inf")]*VexNumber#存放每个蓝点对应的紫边的权重
while len(OuputEdge)<(VexNumber-1):
    #更新紫边权重
    for BluePoint_i in BluePoint:
        for RedPoint_i in RedPoint:
            if EdgeList[BluePoint_i][RedPoint_i]

 

你可能感兴趣的:(python)