如何在我的图中获得最长最短路径?

时间:2021-07-08 06:37:08

标签: python graph networkx

我试图在我的图表上获得所有最长的最短路径,我确实写了这段代码:

    for source in g.nodes:
      for dist in g.nodes:
        if source!=dist:
          distination=len(nx.shortest_path(g,source,dist))
          if distination>3:
            print(source,dist,distination)

这段代码的输出是这样的

    0 1 7
    0 2 7
    0 3 7
    0 4 6
    0 5 6
    0 6 5
    0 7 4
    0 8 7
    0 9 6
    0 10 7
    0 11 8
    0 12 5
    0 13 7
    0 14 8
    0 15 5
    0 16 8
    0 18 5
    0 19 6
    0 20 6
    0 21 6
    0 22 8
    0 23 5
    0 26 7
    0 27 8
    0 28 5
    0 29 8
    0 30 4
    0 31 8

它给了我所需的结果,但是有没有更专业的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用 all_pairs_dijkstra_path_length 为您提供每个节点的所有最短路径,然后您可以循环使用它

ppp=nx.all_pairs_dijkstra_path_length(g)
for i in ppp:
  node=max(i[1], key=i[1].get)
  print(i[0],node,len(nx.shortest_path(g,i[0],node)))