Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从图中得到有向树?_Python_Graph_Tree_Networkx - Fatal编程技术网

Python 如何从图中得到有向树?

Python 如何从图中得到有向树?,python,graph,tree,networkx,Python,Graph,Tree,Networkx,我有一棵树。如何获取根位于4的定向树?要从节点4获取宽度优先搜索的定向树: 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 t

我有一棵树。如何获取根位于4的定向树?

要从节点4获取宽度优先搜索的定向树:

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
tree = nx.bfs_tree(G, 4)



要从节点4获取depfth first search的定向树,请执行以下操作:

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
tree = nx.bfs_tree(G, 4)


图形是通过以下方式生成的:

tree = nx.dfs_tree(G, 4)

这可能是@kalombo想要从G的MST得到一个定向树,根在节点4。在这种情况下,您需要首先构建MST图。e、 g

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')