Network Search: dfs_successors vs. dfs_predecessors

Consider the following chart structure (taken from this question ):

G = networkx.DiGraph()
G.add_edges_from([('n', 'n1'), ('n', 'n2'), ('n', 'n3')])
G.add_edges_from([('n4', 'n41'), ('n1', 'n11'), ('n1', 'n12'), ('n1', 'n13')])
G.add_edges_from([('n2', 'n21'), ('n2', 'n22')])
G.add_edges_from([('n13', 'n131'), ('n22', 'n221')])

which gives:

n---->n1--->n11
 |     |--->n12
 |     |--->n13
 |           |--->n131 
 |--->n2              
 |     |---->n21     
 |     |---->n22     
 |            |--->n221 
 |--->n3

I can do a depth search for successors starting with node nand get:

> dfs_successors(G, 'n')
{'n': ['n1', 'n2', 'n3'],
 'n1': ['n12', 'n13', 'n11'],
 'n13': ['n131'],
 'n131': ['n221'],
 'n2': ['n22', 'n21']}

However, when I do a depth search for predecessors, for example. node n221nothing happens:

> dfs_predecessors(G, 'n221')
{}

I expect the output to be as follows:

{'n221': ['n22', 'n2', 'n']}

What is going on here, and how can I get the expected behavior?

+3
source share
1 answer

The dfs_predecessors () function gives only the immediate predecessor. So, if you say this (DFS from G from node 'n' and look around one link from "n22")

>>> print(networkx.dfs_predecessors(G, 'n')['n221'])
n22

, .

DFS n221 :

>>> T = networkx.dfs_tree(G,'n')

>>> print(networkx.shortest_path(G.reverse(),'n221','n'))
['n221', 'n22', 'n2', 'n']
+4

All Articles