Python NetworkX find a subgraph in a Directed Graph from a node as root

[亡魂溺海] 提交于 2019-12-06 10:51:32

What you want is the function dfs_preorder_nodes(). Here is a little demo based on your data:

import networkx as nx

g = nx.DiGraph()

g.add_edge('A', 'B')
g.add_edge('B', 'C')
g.add_edge('C', 'D')

g.add_edge('A', 'E')
g.add_edge('E', 'F')
g.add_edge('F', 'A')

g.add_edge('B', 'F')
g.add_edge('F', 'G')

print('A:', list(nx.dfs_preorder_nodes(g, 'A')))
print('B:', list(nx.dfs_preorder_nodes(g, 'B')))
print('G:', list(nx.dfs_preorder_nodes(g, 'G')))

Output:

A: ['A', 'B', 'C', 'D', 'F', 'G', 'E']
B: ['B', 'C', 'D', 'F', 'A', 'E', 'G']
G: ['G']

The output includes the starting node. Therefore, if you don't want it, just remove the first element from the list.

Note that dfs_preorder_nodes() returns a generator object. That is why I called list() to get usable output.

nx.ego_graph() does exactly what you describe. Using the example given by @Hai Vu:

g = nx.DiGraph()

g.add_edge('A', 'B')
g.add_edge('B', 'C')
g.add_edge('C', 'D')
g.add_edge('A', 'E')
g.add_edge('E', 'F')
g.add_edge('F', 'A')
g.add_edge('B', 'F')
g.add_edge('F', 'G')

a = nx.ego_graph(g, 'A', radius=100)
a.node
#out: NodeView(('A', 'B', 'C', 'D', 'E', 'F', 'G'))

list(nx.ego_graph(g, 'G', radius=100).node)
#out: ['G']

radius should be an arbitrarily large number if you would like to get all nodes in the tree until the leafs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!