Python: How to find if a path exists between 2 nodes in a graph?

Bruce picture Bruce · Mar 1, 2010 · Viewed 17.7k times · Source

I am using networkx package of Python.

Answer

Denny Abraham Cheriyan picture Denny Abraham Cheriyan · Oct 27, 2013

To check whether there is a path between two nodes in a graph -

>>> import networkx as nx
>>> G=nx.Graph()
>>> G.add_edge(1,2)
>>> G.add_edge(2,3)
>>> nx.has_path(G,1,3)
True
>>> G.add_edge(4,5)
>>> nx.has_path(G,1,5)
False

For more information, please refer has_path — NetworkX 1.7 documentation