How to check whether two nodes are connected?

mcbetz picture mcbetz · Jul 23, 2014 · Viewed 13.6k times · Source

I have a NetworkX graph with four nodes (a,b,c,d) which are partially connected. How can I check whether two nodes are adjacent? For example: How could I assert that a and d are not adjacent?

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)

I tried the following, but failed:

nx.is_connected(G) # I assume it checks whether edges are connected at all
nx.connected_components(G) # outputs an object that I can make no use of

Answer

mdml picture mdml · Jul 23, 2014

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).