Note
Go to the end to download the full example code.
最小生成树#
最小生成树(MST)是加权连通图中边的一个子集,它以最小的可能总边权重连接所有顶点。minimum_spanning_tree
函数用于比较原始图与其最小生成树。
import networkx as nx
import matplotlib.pyplot as plt
# 创建一个图
G = nx.Graph()
G.add_edges_from(
[
(0, 1, {"weight": 4}),
(0, 7, {"weight": 8}),
(1, 7, {"weight": 11}),
(1, 2, {"weight": 8}),
(2, 8, {"weight": 2}),
(2, 5, {"weight": 4}),
(2, 3, {"weight": 7}),
(3, 4, {"weight": 9}),
(3, 5, {"weight": 14}),
(4, 5, {"weight": 10}),
(5, 6, {"weight": 2}),
(6, 8, {"weight": 6}),
(7, 8, {"weight": 7}),
]
)
# 找到最小生成树
T = nx.minimum_spanning_tree(G)
# 可视化图和最小生成树
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_color="lightblue", node_size=500)
nx.draw_networkx_edges(G, pos, edge_color="grey")
nx.draw_networkx_labels(G, pos, font_size=12, font_family="sans-serif")
nx.draw_networkx_edge_labels(
G, pos, edge_labels={(u, v): d["weight"] for u, v, d in G.edges(data=True)}
)
nx.draw_networkx_edges(T, pos, edge_color="green", width=2)
plt.axis("off")
plt.show()
Total running time of the script: (0 minutes 0.039 seconds)