Consider a directed graph where the weight of its edges can be one of x, 2x, or 3x (x is a positive integer), efficiently compute the least-cost path from source to destination.

For example, consider the following graph:

 
Least Cost Path

If the source is 1 and destination is 3, the least-cost path from source to destination is [1, 4, 3] having cost 2.

If the source is 0 and destination is 2, the least-cost path from source to destination is [0, 4, 2] having cost 3.

Practice this problem

We know that Breadth–first search (BFS) can be used to find the shortest path in an unweighted graph or a weighted graph having the same cost of all its edges. BFS runs in O(E + V) time, where E is the total number of the edges and V is the total number of vertices in the graph. But if the edges in the graph are weighted with different costs, then the recommended algorithm is Dijkstra’s Algorithm, which takes O(E.log(V)) time.

Can we use BFS?

The idea is to modify the input graph so that all its edges have the same weight. For edges having weight 3x, split them into three edges of weight x each. Similarly, edges having weight 2x gets split into two edges of weight x each. Nothing needs to be done for edges already having weight x. Special care has to be taken while introducing new edges in the graph such that no new routes are introduced into the graph. To split an edge of weight 3x, create two new vertices in the graph instead of using existing vertices. Similarly, to split edge having weight 2x, create one new vertex. Let’s illustrate this with the help of a diagram.

Split edge (v, u) having weight 3x into three edges (v, v+n), (v+n, v+2N), and (v+2N, u) each having weight x.

Spilt edges into two

Split edge (v, u) having weight 2x into two edges (v, v+n) and (v+n, u) each having weight x.

Spilt edges into one

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

C++


Download  Run Code

Output:

The least-cost path between 0 and 2 is 0 4 2 having cost 3

Java


Download  Run Code

Output:

The least-cost path between 0 and 2 is 0 4 2 having cost 3

Python


Download  Run Code

Output:

The least-cost path between 0 and 2 is 0 4 2 having cost 3