Given a weighted digraph (directed graph), find the least-cost path from a given source to a given destination with exactly m edges.

For example, consider the following graph,

 
Shortest Path

Let source = 0, destination = 3, number of edges (m) = 4.
 
The graph has 3 routes from source 0 to destination 3 with 4 edges.
 
0—1—5—2—3 having cost 17
0—1—6—5—3 having cost 19
0—6—5—2—3 having cost 8
 
The solution should return the least-cost, i.e., 8.

Practice this problem

Whenever we see the term shortest, the first thing we should think about is doing a BFS traversal. So, here also, we start BFS traversal from the given source vertex. Usually, BFS doesn’t explore already discovered vertices again, but here we do the opposite. To cover all possible paths from source to destination, remove this check from BFS. But what 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 don’t consider nodes having a BFS depth of more than m.

The solution below maintains the following information in a BFS queue node:

  • The current vertex number.
  • The current depth of BFS (i.e., how far the current node is from the source?).
  • The cost of the current path chosen so far.

Whenever we encounter any node whose cost of a path is more and required BFS depth is reached, update the result. The BFS will terminate when we have explored every path in the given graph or BFS depth exceeds m.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

8

Java


Download  Run Code

Output:

8

Python


Download  Run Code

Output:

8

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 least-cost path.