繁体   English   中英

在不添加权重属性的情况下查找图中两个节点之间的所有最短路径

[英]Find all shortest paths between two nodes in a graph without adding weight attributes

给定有向图G 、源节点s 、目标节点t和权重 function f 是否可以计算 st using.networkx 之间的所有最短路径而不将权重添加为边属性?

对于单个最短路径,我使用的是single_source_dijkstra

shortest_path = nx.single_source_dijkstra(G, source=s, target=t, weight=f)

我知道如果我将权重添加为边缘属性,我可以使用all_shortest_paths

all_shortest_paths = nx.all_shortest_paths(G, source=s, target=t, weight='weight', method='dijkstra')

是否有类似的计算所有最短路径的方法,我不必为每条边添加权重属性,而是输入权重 function f 并获取(路径长度,路径)元组列表?

我认为您有两种易于实现的可能性。 A:定义一个 function,它返回给边的特定权重,作为属性添加到图形,然后在刚创建的边属性上运行 all_shortest_paths。

B:简单地遍历图中的所有节点:

results = []
for n1 in G.nodes():
    for n2 in G.nodes():
        shortest_path = nx.single_source_dijkstra(G, source=n1, target=n2, weight=f)
        results.append(shortest_path)
        

编辑:

您可以使用

nx.all_shortest_paths = nx.all_shortest_paths(G, source=s, target=t, weight=cost_function, method='dijkstra')

使用自定义 function。它将根据您的指标正确返回所有最短路径。 但请注意,据我了解 .networkx 中的实现,这将计算所有节点的最短路径,然后根据您的源节点和目标节点简单地作为选择返回。

它不会返回你的路径长度,因为它们都是一样的......如果你必须......你可以把它弄出来......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM