简体   繁体   English

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

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

Given a directed graph G , source node s , target node t and a weight function f .给定有向图G 、源节点s 、目标节点t和权重 function f Is it possible to calculate all shortest paths between st using.networkx without adding the weights as edge attributes?是否可以计算 st using.networkx 之间的所有最短路径而不将权重添加为边属性?

For a single shortest path I am using single_source_dijkstra对于单个最短路径,我使用的是single_source_dijkstra

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

I know that if I would add the weights as edge attributes, I could use all_shortest_paths我知道如果我将权重添加为边缘属性,我可以使用all_shortest_paths

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

Is there a similar way of computing all shortest paths, where I don't have to add weight attributes to every edge and instead input a weight function f and get a list of (path_length, path)-tuples?是否有类似的计算所有最短路径的方法,我不必为每条边添加权重属性,而是输入权重 function f 并获取(路径长度,路径)元组列表?

I think you have two easy to implement possibilities.我认为您有两种易于实现的可能性。 A: Define a function, that returns the sepcific weights you to an edge, add as attribute to graph, then run the all_shortest_paths on the edge attributed you just created. A:定义一个 function,它返回给边的特定权重,作为属性添加到图形,然后在刚创建的边属性上运行 all_shortest_paths。

B: Simply iterate over all nodes in the graph: 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)
        

EDIT:编辑:

You can use您可以使用

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

with a custom function. It will correctly return all shortest paths based on your metric.使用自定义 function。它将根据您的指标正确返回所有最短路径。 But be aware, as far as I understand the implementation in.networkx, this will calculate the shortest paths for all nodes, then simply return as selection based on your source and target node.但请注意,据我了解 .networkx 中的实现,这将计算所有节点的最短路径,然后根据您的源节点和目标节点简单地作为选择返回。

It will not return you the path lenghts, as they are all the same... You can get it out if you would have to...它不会返回你的路径长度,因为它们都是一样的......如果你必须......你可以把它弄出来......

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

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