从文档看来,您可以使用shortest_simple_paths 从最短路径开始生成两个顶点之间的所有简单路径:
https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.simple_paths.shortest_simple_paths.html#
编辑:多图的答案
这是获得您正在寻找的答案的非常粗略的解决方案。我认为它只适用于小图:
G = nx.MultiDiGraph()
G.add_edge(1, 2, **{'weight': 15, 'max': 3})
G.add_edge(1, 3, **{'weight': 30, 'max': 4})
G.add_edge(2, 3, **{'weight': 20, 'max': 3})
G.add_edge(2, 3, **{'weight': 20, 'max': 5})
# get all paths and convert them to tuples so that we can
# deduplicate them
paths = [tuple(p) for p in nx.all_simple_paths(G, 1, 3)]
# sort the paths according to the number of nodes in the path
print(sorted(set(paths), key=lambda x:len(x)))
编辑 2:加权多重图的答案
这个有点复杂,你需要自己编写“路径分数”函数并传递给分拣机。
G = nx.MultiDiGraph()
G.add_edge(1, 2, **{'weight': 15, 'max': 3})
G.add_edge(1, 3, **{'weight': 30, 'max': 4})
G.add_edge(2, 3, **{'weight': 20, 'max': 3})
G.add_edge(2, 3, **{'weight': 20, 'max': 5})
def get_edge_weight(u, v):
"""Return the minimum weight of all edges between nodes u and v."""
return min([e['weight'] for e in G.get_edge_data(u, v).values()])
def weighted_path_score(path):
"""Sum of edge weights in path."""
edges = zip(path, path[1:])
return sum(get_edge_weight(u, v) for u, v in edges)
paths = [tuple(p) for p in nx.all_simple_paths(G, 1, 3)]
# sort using the weighted path score
print(sorted(set(paths), key=weighted_path_score))
您可以使用边权重并检查返回路径的顺序是否符合它(例如,将高权重设置为边 1-3 将导致路径 (1,2,3) 首先列出)。