Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find path with highest sum in a weighted networkx graph?

I have a directed networkx weighted graph. How do I find the path with the biggest sum of weights?

like image 858
nitroman Avatar asked Feb 12 '23 20:02

nitroman


1 Answers

You can use all_simple_paths and check the maximum. Assuming you have a function that takes a path and gives you the sum of the weights:

heaviest_path = max((path for path in nx.all_simple_paths(G, source, dest)),
                    key=lambda path: get_weight(path))

In case two of them have the same weight, this will give you the first one found.

like image 173
Davidmh Avatar answered Feb 15 '23 09:02

Davidmh