# 将需要输出最小生成树的带权图的每条边按以下格式写好
Text_edge = [("v1", "v2", 20), ("v1", "v7", 1),
("v1", "v6", 23), ("v2", "v7", 4),
("v2", "v3", 15), ("v6", "v7", 36),
("v3", "v7", 9), ("v6", "v5", 28),
("v3", "v4", 3), ("v7", "v5", 25),
("v7", "v4", 16), ("v4", "v5", 17)]
nodes = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7']
# 对每条边按权值从小到大排序
Text_edge.sort(key=lambda x: x[2])
ori_roots_dict = dict()
for i in nodes:
ori_roots_dict[i] = i
# 寻找根节点函数,最开始,根节点都是初始化为自己,返回根节点(就是上面的ori_roots_dict)
def find_root(x):
if ori_roots_dict[x] != x:
ori_roots_dict[x] = find_root(ori_roots_dict[x])
return ori_roots_dict[x]
# 用out列表存储生成的最小生成树
out = []
# 确定循环的次数,n为需要添加的边数=顶点数-1
n = len(nodes)-1
# 循环
for edge in Text_edge:
v1, v2, _ = edge
if find_root(v1) != find_root(v2):
ori_roots_dict[find_root(v2)] = find_root(v1)
out.append(edge)
print('添加第'+str(7-n)+'条边后:')
n -= 1
print(ori_roots_dict)
print(out)
if n == 0:
break
# 运行结果:
"""
添加第1条边后:
{'v1': 'v1', 'v2': 'v2', 'v3': 'v3', 'v4': 'v4', 'v5': 'v5', 'v6': 'v6', 'v7': 'v1'}
[('v1', 'v7', 1)]
添加第2条边后:
{'v1': 'v1', 'v2': 'v2', 'v3': 'v3', 'v4': 'v3', 'v5': 'v5', 'v6': 'v6', 'v7': 'v1'}
[('v1', 'v7', 1), ('v3', 'v4', 3)]
添加第3条边后:
{'v1': 'v2', 'v2': 'v2', 'v3': 'v3', 'v4': 'v3', 'v5': 'v5', 'v6': 'v6', 'v7': 'v1'}
[('v1', 'v7', 1), ('v3', 'v4', 3), ('v2', 'v7', 4)]
添加第4条边后:
{'v1': 'v2', 'v2': 'v3', 'v3': 'v3', 'v4': 'v3', 'v5': 'v5', 'v6': 'v6', 'v7': 'v2'}
[('v1', 'v7', 1), ('v3', 'v4', 3), ('v2', 'v7', 4), ('v3', 'v7', 9)]
添加第5条边后:
{'v1': 'v2', 'v2': 'v3', 'v3': 'v3', 'v4': 'v3', 'v5': 'v3', 'v6': 'v6', 'v7': 'v3'}
[('v1', 'v7', 1), ('v3', 'v4', 3), ('v2', 'v7', 4), ('v3', 'v7', 9), ('v4', 'v5', 17)]
添加第6条边后:
{'v1': 'v3', 'v2': 'v3', 'v3': 'v3', 'v4': 'v3', 'v5': 'v3', 'v6': 'v3', 'v7': 'v3'}
[('v1', 'v7', 1), ('v3', 'v4', 3), ('v2', 'v7', 4), ('v3', 'v7', 9), ('v4', 'v5', 17), ('v1', 'v6', 23)]
"""
Python之最小生成树Kruskal算法(避圈法)
最新推荐文章于 2024-11-11 21:30:41 发布