qwurey的文章写的很好懂了,但是自己代码再写出来确实不一样,主要还是练一下基本功,自己基本功还不够,代码勉强凑合吧,可能过多一阵自己回来再看就能写出更好的。作者的图很好看,用什么画的呢。
VISITED = 999999 # 表示已经加入MST
DISCONNECT = 10000 # 表示无通路
def Prim(graph: dict, start: str) -> list:
lowcost = [DISCONNECT]*len(graph)
lowcost[int(start)-1] = VISITED
mst = [start]*len(graph) # 记录顶点的历史更新,用于回溯
mst[int(start)-1] = 0
visted = []
visted.append(start)
vist = [] # 用于输出
node = start
# 更新lowcost和mst
while any(mst):
lowcost, mst = update(graph[node], node, lowcost, mst)
if node == mst[lowcost.index(min(lowcost))]:
vist.append(node + '->' + str(lowcost.index(min(lowcost))+1))
node, mst[lowcost.index(min(lowcost))] = str(lowcost.index(min(lowcost)) + 1), 0 # 找出到开始的顶点权值最小的顶点
else:
vist.append(str(mst[lowcost.index(min(lowcost))]) + '->' + str(lowcost.index(min(lowcost))+1))
node, mst[lowcost.index(min(lowcost))] = str(lowcost.index(min(lowcost))+1), 0
lowcost[lowcost.index(min(lowcost))] = VISITED
visted.append(node)
return vist
def update(edge: list, thisNode: str, lowcost: list, mst: list):
for i in edge:
if lowcost[int(i[0]) - 1] != VISITED and i[1] < lowcost[int(i[0]) - 1]:
lowcost[int(i[0]) - 1] = i[1]
mst[int(i[0])-1] = thisNode
return lowcost, mst
if __name__ == "__main__":
G = {
'1': [['2', 6], ['3', 1], ['4', 5]],
'2': [['1', 6], ['3', 5], ['5', 3]],
'3': [['1', 1], ['2', 5], ['4', 5], ['5', 6], ['6', 4]],
'4': [['1', 5], ['3', 5], ['6', 2]],
'5': [['2', 3], ['3', 6], ['6', 6]],
'6': [['3', 4], ['4', 2], ['5', 6]]}
v = Prim(G, '1')
for i in v:
print(i)
Connected to pydev debugger (build 191.7141.48)
1->3
3->6
6->4
3->2
2->5