如何为构成最小生成树的图的边着色

How to color the edges of the graph that make the minimal spanning tree

我有一个具有 4 个节点的完整图 G。我需要给构成最小生成树的边上色。我如何使用 networkx 和 python 做到这一点?

networkx.draw takes an optional edge_color keyword argument which allows you to specify the color of individual edges. Using the minimum_spanning_tree 函数,如果一条边在最小生成树内,我们可以将其着色为红色,否则为黑色。

代码

import networkx as nx
G = nx.complete_graph(4)

mst = nx.minimum_spanning_tree(G)

edge_colors = ['red' if e in mst.edges else 'black' for e in G.edges]

nx.draw(G, edge_color=edge_colors)

输出