Search code examples
pythonnetworkx

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?


Solution

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