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
Approach: Either Breadth First Search (BFS) or Depth First Search (DFS) can be used to find path between two vertices. Take the first vertex as a source in BFS (or DFS), follow the standard BFS (or DFS). If the second vertex is found in our traversal, then return true else return false.
A graph is said to be connected if every pair of vertices in the graph is connected. This means that there is a path between every pair of vertices. An undirected graph that is not connected is called disconnected.
A graph is connected if for any two vertices x, y ∈ V (G), there is a path whose endpoints are x and y. A connected graph G is called 2-connected, if for every vertex x ∈ V (G), G − x is connected. A separating set or vertex cut of a connected graph G is a set S ⊂ V (G) such that G − S is disconnected.
An edge is incident on the two nodes it connects. Any two nodes connected by an edge or any two edges connected by a node are said to be adjacent.
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
).
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With