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

时间:2015-03-15 22:12:26

标签: python networkx shortest-path

我有无向图

我想从网络中两个节点之间所有最短路径长度的列表中计算最大值,我想怎样做才能做到这一点?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

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

# 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是一个列表。 max_shortest_path的所有元素都是相等长度的列表。

len(max_shortest_path[0])将为您提供图表中最大最短路径的长度

max_shortest_path的元素是这个长度的路径。

相关问题