Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using networkx package of Python.

like image 899
Bruce Avatar asked Mar 01 '10 03:03

Bruce


People also ask

How do you check if a path exists between two nodes in a graph?

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.

Is there a path in directed graph?

A directed path (sometimes called dipath) in a directed graph is a finite or infinite sequence of edges which joins a sequence of distinct vertices, but with the added restriction that the edges be all directed in the same direction.


2 Answers

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

like image 77
Denny Abraham Cheriyan Avatar answered Oct 05 '22 22:10

Denny Abraham Cheriyan


>>> import networkx as nx
>>> G=nx.empty_graph()
>>> G.add_edge(1,2)
>>> G.add_edge(2,3)
>>> G.add_edge(4,5)
>>> nx.path.bidirectional_dijkstra(G,1,2)
(1, [1, 2])
>>> nx.path.bidirectional_dijkstra(G,1,3)
(2, [1, 2, 3])
>>> nx.path.bidirectional_dijkstra(G,1,4)
False
>>> nx.path.bidirectional_dijkstra(G,1,5)
False
>>> 

You can also use the result as a boolean value

>>> if nx.path.bidirectional_dijkstra(G,1,2): print "path exists"
... 
path exists
>>> if nx.path.bidirectional_dijkstra(G,1,4): print "path exists"
... 
>>> 
like image 36
John La Rooy Avatar answered Oct 05 '22 22:10

John La Rooy