【问题标题】:python graph find alternative fastest routespython graph找到替代的最快路线
【发布时间】:2018-08-28 14:25:56
【问题描述】:

我有一个非常大的网络(来自整个国家的道路网络),我将其加载到 networkx 以计算点之间的距离。如果我只想知道两点之间最快的路线,这很好用并且非常快。但是,我也想知道替代路线(如果一条路线是例如 1000 公里,我也想知道 1010、1018、1032 和 1042 公里的替代路线)。我想过使用networkx的all_simple_paths函数,但这真的很慢,需要几天才能运行。有人可以建议一种替代方法吗?

谢谢!

【问题讨论】:

    标签: python networkx shortest-path


    【解决方案1】:

    Networkx 有一个内置算法,可以生成最短路径,然后是下一条最短路径,然后是下一条最短路径,等等。

    shortest_simple_paths

    例如:

    import networkx as nx
    G = nx.Graph()
    G.add_edges_from([[0,1], [1,2], [2,3], [0,2], [0,3]])
    X = nx.shortest_simple_paths(G, 0, 3) #generator to find paths from 0 to 3 in order from shortest to longest.
    for x in X:
        print(x)
    > [0, 3]
    > [0, 2, 3]
    > [0, 1, 2, 3]
    #note that X is now empty because it is a generator
    for x in X:
        print(x) #nothing to see here
    > 
    #if you just want the first two:
    X = nx.shortest_simple_paths(G, 0, 3)
    for k in range(2):
        print(next(X))
    > [0, 3]
    > [0, 2, 3]
    

    这个算法会找到所有的路径,但是它被设置成它只做额外的工作来计算第 k 条最短路径,当它被要求时,它会忘记它。有关生成器的更多信息,请参阅 Understanding generators in Python

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多