How to find shortest path in a weighted graph using networkx?

前端 未结 1 1545
渐次进展
渐次进展 2020-12-30 10:25

I\'m using the networkx package in Python 2.7 Enthought distribution to calculate shortest paths between a network of seaports. It\'s working fine

相关标签:
1条回答
  • 2020-12-30 11:11

    Experimenting a bit, it appears that nx.dijkstra_path raises a misleading exception when the origin and destination nodes are the same:

    >>> import networkx as nx
    >>> g = nx.Graph()
    >>> g.add_edge('a', 'b', distance=0.3)
    >>> g.add_edge('a', 'c', distance=0.7)
    >>> nx.dijkstra_path_length(g, 'b', 'c', 'distance')
    1.0
    >>> nx.dijkstra_path(g, 'b', 'c', 'distance')
    ['b', 'a', 'c']
    >>> nx.dijkstra_path_length(g, 'b', 'b', 'distance')
    0
    >>> nx.dijkstra_path(g, 'b', 'b', 'distance')
    Traceback (most recent call last):
      File "<pyshell#7>", line 1, in <module>
        nx.dijkstra_path(g, 'b', 'b', 'distance')
      File "C:\Users\barberm\AppData\Roaming\Python\Python27\site-packages\networkx\algorithms\shortest_paths\weighted.py", line 74, in dijkstra_path
        return path[target]
    TypeError: list indices must be integers, not str
    

    So just make an explicit test whether destination and origin are the same, and handle it separately when they are.

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