def prim(G):
dis=0
x=[1]
select=G[0] #edge can be selected next time
for i in range(len(G)-1): #add n-1 edge
for key in select.keys(): #select the next min edge
if select[key]==min(select.values()):
dis+=select[key]
x.append(key) #add the selected node into x[]
#update the select{}
for keyG in G[key-1]:
if keyG not in x: #update the already arrivble node
if keyG in select.keys():
select[keyG]=min(G[key-1][keyG],select[keyG])
else: #add new arrivble node
select[keyG]=G[key-1][keyG]
del select[key] #delete the already select edge
print 'the order is:'
print x
return dis
G=[{2:1,3:2},
{1:1,3:6,4:11},
{1:2,2:6,4:9,5:13},
{2:11,3:9,5:7,6:3},
{3:13,4:7,6:4},
{4:3,5:4}]
G1=[{2:1,3:6,4:2},
{1:1,3:7,4:2},
{1:6,2:7,4:9,5:4,6:3},
{1:2,2:2,3:9,5:7,6:6},
{3:4,4:7,6:3},
{3:3,4:6,5:3}]
print 'the distance is %d'%prim(G)
print 'the distance is %d'%prim(G1)
思路:
做n-1次循环
每次检查可选边字典select{},选最小的加入(初始为1节点的边集)
加入边 的 另一端点 加入x[ ]
更新可选边select{}:
有同样的到达点,取小值(因python字典一键只能一值)
不一样直接加入
删除加入边
建了一个select可选边的字典,比原版的稍有变化。
下次写一个书上的原版的prim算法