-1

I may be overthinking this and be missing something obvious, but I was wondering which NetworkX algorithm I could use to achieve the following:

Given a DiGraph such as:

Simple DiGraph

And a list of nodes such as: Q1, Q2

Find all nodes which are connected to (or in other words children of) Q1 and Q2, the results would be as following:

Q1

Q2

Which algorithm would accomplish this?

beaker
  • 16,331
  • 3
  • 32
  • 49

2 Answers2

0

Looks like you just need to make a recursion over networkx.Digraph.predecessors

al-dev
  • 256
  • 2
  • 8
0

A first way is to use a list, visit the predecessor of each node starting from your node and put it in the list, building in this way a tree with the nodes you find.

Another way is to use a visit (DFS or BFS) on the graph reversing the edges.

Consider the following example where I build a bfs tree starting at Node "Q1".

import networkx as nx

g = nx.DiGraph()

g.add_edges_from([("M1","Q1"),("I1","M1"),("I2","M1"),("I3","M1"),("I3","M2"),("M2","Q2")])

#creating a graph with the edges reversed
g2 = nx.DiGraph()
g2.add_edges_from([(v,u) for (u,v) in g.edges()])

t = nx.bfs_tree(g2, "Q1")

for (u,v) in t.edges():
    t.remove_edge(u,v)
    t.add_edge(v,u)


print(t.nodes(),t.edges())
# ['Q1', 'M1', 'I1', 'I2', 'I3'] [('M1', 'Q1'), ('I1', 'M1'), ('I2', 'M1'), ('I3', 'M1')]
abc
  • 11,579
  • 2
  • 26
  • 51