In [4]:
%matplotlib inline

import networkx as nx

In [34]:
# test DFS
G = nx.DiGraph()
G.add_nodes_from([0,1,2,3,4])
G.add_edges_from([[0,1],[0,2],[2,3],[2,4]])


print(nx.dfs_predecessors(G, 0))


{1: 0, 2: 0, 3: 2, 4: 2}

In [49]:
pos = nx.shell_layout(G)

nx.draw_networkx_nodes(G, pos, node_color='b', alpha=0.2, node_size=200)
nx.draw_networkx_edges(G, pos, alpha=0.2)

start = 2
connected = nx.dfs_predecessors(G.reverse(), start)
#connected = nx.dfs_predecessors(G, start)
print(connected)
nx.draw_networkx_nodes(G.subgraph(connected), pos, node_color='r', alpha=0.2, node_size=200)

nx.draw_networkx_nodes(G.subgraph([start]), pos, node_color='c', alpha=0.2, node_size=400)

nx.draw_networkx_labels(G, pos)

# thick line can


{0: 2}
Out[49]:
{0: <matplotlib.text.Text at 0x158d1d30f28>,
 1: <matplotlib.text.Text at 0x158d1d3ec18>,
 2: <matplotlib.text.Text at 0x158d1d441d0>,
 3: <matplotlib.text.Text at 0x158d1d44588>,
 4: <matplotlib.text.Text at 0x158d1d44b00>}