管道铺设施工的最佳方案选择:N ( N >10)个居民之间需要铺设煤气管道。假设任意两个居民之间都可以铺设煤气管道,但代价不同。事先将任意两个居民之间铺设煤气管道的代价存入磁盘文件中。设计 T 个最佳方案使得这 N 个居民之间铺设煤气管道所需代价最少,并希望以图形方式在屏幕上输出结果。
代码:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 使用SimHei字体
plt.rcParams['axes.unicode_minus'] = False # 正确显示负号
import networkx as nx
import matplotlib.pyplot as plt
def prim(G, start):
T = nx.Graph()
T.add_node(start)
while len(T.nodes) < len(G.nodes):
# 选择具有最小权重的边,但目标节点不在 T 中
edge = min((e for e in G.edges(T.nodes) if e[1] not in T.nodes), key=lambda e: G.get_edge_data(*e)['weight'])
T.add_edge(*edge)
return T
# 创建一个图
G = nx.Graph()
edges = [(0, 1, 2), (1, 2, 3), (2, 3, 7), (3, 4, 9), (4, 0, 5), (0, 2, 6), (1, 3, 8)]
G.add_weighted_edges_from(edges)
# 计算最小生成树
T = prim(G, 0)
# 绘制原图
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.title('原始图')
plt.show()
# 绘制最小生成树
nx.draw_networkx(T, pos)
labels = nx.get_edge_attributes(T, 'weight')
nx.draw_networkx_edge_labels(T, pos, edge_labels=labels)
plt.title('最小生成树')
plt.show()
输出图: