gpt4 book ai didi

python - 我怎样才能从图中得到有向树?

转载 作者:太空狗 更新时间:2023-10-29 22:23:02 25 4
gpt4 key购买 nike

import networkx as nx
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(3,5)
G.add_edge(4,6)
G.add_edge(1,6)
G.add_edge(2,6)
G.add_edge(7,8)
G.add_edge(9,8)
mst=nx.prim_mst(G)# a generator of MST edges

我有一棵树。如何获得根为 4 的有向树?

最佳答案

从节点4获取广度优先搜索的有向树:

tree = nx.bfs_tree(G, 4)

enter image description here


从节点4获取深度优先搜索的有向树:

tree = nx.dfs_tree(G, 4)

enter image description here


图表是这样生成的:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(3,5)
G.add_edge(4,6)
G.add_edge(1,6)
G.add_edge(2,6)
G.add_edge(7,8)
G.add_edge(9,8)

tree = nx.bfs_tree(G, 4)
nx.draw(tree)
plt.savefig('/tmp/bfs_image.png')

关于python - 我怎样才能从图中得到有向树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15403407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com