How to check whether two nodes are connected?
This is the recommended way:
import networkx as nx
G=nx.Graph()
G.add_edge('a','b',weight=1)
G.add_edge('a','c',weight=1)
G.add_edge('c','d',weight=1)
print(G.has_edge('a','d')) # False
print('d' in G['a']) # False, faster
print('d' not in G['a']) # True
One way to check whether two nodes are connected with NetworkX is to check whether a node u
is a neighbor of another node v
.
>>> def nodes_connected(u, v):
... return u in G.neighbors(v)
...
>>> nodes_connected("a", "d")
False
>>> nodes_connected("a", "c")
True
Note that networkx.is_connected
checks whether every node in a graph G is reachable from every other node in G. This is equivalent to saying that there is one connected component in G (i.e. len(nx.connected_components(G)) == 1
).
I think you ask about "how to know two nodes are reachable each other" It can be solve by this code.
networkx.algorithms.descendants(G, target_nodes)
it returns all reachable nodes from target_nodes
in G
.