views:

194

answers:

4

I am using networkx package of Python.

+1  A: 
The MYYN
What if path does not exist between 2 given nodes? What does the function return then?
Bruce
I don't want to find the shortest path. I just want to know if a path exists between 2 given nodes.
Bruce
+2  A: 
>>> 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"
... 
>>> 
gnibbler
+1  A: 

Use

shortest_path(G, source, target)

or one of the Shortest Path methods. Stay clear of the methods which return paths between all nodes however if you merely have two specific nodes to test for connectivity.

mjv
A: 
for e in G.edges():
    if node1 in e and node2 in e:
        return True
return False
inspectorG4dget
This returns true only if an edge exists directly between the nodes. A path can be longer than one edge.
John Källén