习题6.3

1.代码实现

点击查看代码
import numpy as np
import networkx as nx
import pylab as plt
L = [(1, 2, 20), (1, 5, 15), (2, 5, 25), (2, 3, 20), (2, 4, 60), (3, 5, 18), (3, 4, 30), (5, 4, 35), (4, 6, 15),
     (4, 6, 10)]
G = nx.Graph()
G.add_weighted_edges_from(L)
T = nx.minimum_spanning_tree(G)
c = nx.to_numpy_array(T)
print("邻接矩阵c=\n", c)
w = c.sum() / 2
print("最小生成树的权重W=", w)
pos = nx.circular_layout(G)
plt.subplot(121)
nx.draw(G, pos, with_labels=True, font_size=13)
w1 = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=w1)
plt.subplot(122)
nx.draw(T, pos, with_labels=True, font_weight='bold')
w2 = nx.get_edge_attributes(T, 'weight')
nx.draw_networkx_edge_labels(T, pos, edge_labels=w2)
plt.show()

2.运行结果

posted on 2024-10-27 16:40  克卜勒星球  阅读(3)  评论(0编辑  收藏  举报

导航