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

后端 未结 5 2222
野性不改
野性不改 2021-01-01 17:55

I am using networkx package of Python.

相关标签:
5条回答
  • 2021-01-01 18:06

    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.

    0 讨论(0)
  • 2021-01-01 18:17
    • dijkstra_path(G, source, target)

      Returns the shortest path from source to target in a weighted graph G.

    0 讨论(0)
  • 2021-01-01 18:20
    >>> 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"
    ... 
    >>> 
    
    0 讨论(0)
  • 2021-01-01 18:28

    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

    0 讨论(0)
  • 2021-01-01 18:29

    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.

    0 讨论(0)
提交回复
热议问题