代码之家  ›  专栏  ›  技术社区  ›  BKS

两个节点之间所有最短路径列表中的最大值

  •  0
  • BKS  · 技术社区  · 9 年前

    我有一个无向图

    我想从网络中两个节点之间所有最短路径长度的列表中计算最大值,有什么想法可以做到吗?

    2 回复  |  直到 9 年前
        1
  •  1
  •   jedwards    9 年前

    如果只想考虑源和目标的某些顶点子集,可以执行以下操作:

    # Change these to fit your needs
    sources = G.nodes()     # For example, sources = [0,1,4]
    targets = G.nodes()
    
    max_shortest_path = None
    for (s,t) in itertools.product(sources, targets):
        if s == t: continue # Ignore
        shortest_paths = list(nx.all_shortest_paths(G, s, t))
        path_len = len(shortest_paths[0])
        if max_shortest_path is None or path_len > len(max_shortest_path[0]):
            max_shortest_path = list(shortest_paths)    # Copy shortest_paths list
        elif path_len == len(max_shortest_path[0]):
            max_shortest_path.extend(shortest_paths)
    

    后来 max_shortest_path 是一个列表。的所有元素 最大最短路径 是长度相等的列表。

    len(max_shortest_path[0]) 会给你 图中的最大最短路径。

    的元素 最大最短路径 是这个长度的路径。

        2
  •  0
  •   Aric    9 年前