I am using networkx package of Python.
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.
Returns the shortest path from source to target in a weighted graph G.
>>> 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"
...
>>>
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
Using a disjoint set data structure:
Create a singleton set for every vertex in the graph, then union the sets containing each of the pair of vertices for every edge in the graph.
Finally, you know a path exists between two vertices if they are in the same set.
See the wikipedia page on the disjoint set data structure.
This is much more efficient than using a path finding algorithm.