Given a weighted undirected graph, find the maximum cost path from a given source to any other vertex in the graph which is greater than a given cost. The path should not contain any cycles.

For example, consider the following graph,

Maximum cost path

Let source = 0 and cost = 50.

The maximum cost route from source vertex 0 is 0—6—7—1—2—5—3—4, having cost 51, which is more than cost 50. The solution should return 51.

Maximum cost path solution

Practice this problem

The idea is to do a Breadth–first search (BFS) traversal. BFS is generally used to find the shortest paths in graphs/matrices, but we can modify normal BFS to meet our requirements. By modifying BFS, we don’t mean using a priority queue that picks up the maximum weighted edge at every step, as that approach will fail. A low-weight edge can also be involved in the maximum cost path as there might be higher weight edges connected through it.

So, how can we use BFS?

Usually, BFS doesn’t explore already discovered vertices again, but here we do the opposite. To cover all possible paths from a given source, remove this check from BFS. But if the graph contains a cycle, removing this check will cause the program to go into an infinite loop. We can easily handle that if we maintain a list of nodes visited so far in the current path for a node in a queue. Basically, we maintain three things in the BFS queue node:

  • The current vertex number.
  • The cost of the current path chosen so far.
  • The set of nodes visited so far in the current path.

Whenever we encounter any node whose cost of a path is more, update the result. The BFS will terminate when we have explored every path that doesn’t result in a cycle.

This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

51

Java


Download  Run Code

Output:

51

Python


Download  Run Code

Output:

51

The time complexity of the above solution is O(V.E), where V and E are the total number of vertices and edges in the graph, respectively.

 
Exercise: Extend the solution to print the maximum cost path from source to destination.