nitroman
nitroman

Reputation: 673

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?

Upvotes: 6

Views: 5496

Answers (1)

Davidmh
Davidmh

Reputation: 3865

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.

Upvotes: 10

Related Questions