简体   繁体   中英

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 . Is it possible to calculate all shortest paths between st using.networkx without adding the weights as edge attributes?

For a single shortest path I am using 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 = 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?

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.

B: Simply iterate over all nodes in the graph:

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. 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.

It will not return you the path lenghts, as they are all the same... You can get it out if you would have to...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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