Given a weighted directed graph represented by a 2D array edges[][], where each element edges[i] = {u, v, w} represents a directed edge from vertex u to vertex v with cost w, find the minimum cost required to travel from a given source vertex src to a destination vertex dst. You are also given an integer k representing the maximum number of nodes allowed in the path. Return the minimum possible cost of such a path containing at most k nodes. If no such path exists, return -1.
There can be a route marked with a red arrow that takes cost = Â 10+10+10+10 = 40 using three nodes. And route marked with green arrow takes cost = 10+20+30=60 using two nodes. But since there can be at most 2 nodes, the answer will be 60.
Using BFS Traversal - O(k*E) Time and O(V + E) Space
Use Breadth-First Search (BFS) to explore all possible paths level by level while keeping track of the minimum cost to reach each node. Since each BFS level represents one more node in the path, we continue the traversal only up to k nodes. Whenever a cheaper cost to reach a node is found, we update it and push that node into the queue for further exploration.
Steps:
Increase the value of k by 1 to account for the destination node.
Create an adjacency list from the given graph.
Initialize a prices[] array with -1 to store the minimum cost to reach each node.
Initialize a queue and push {src, 0} into it, where 0 is the current cost.
Run BFS until the queue becomes empty or k becomes 0.
For every node popped from the queue, traverse all its adjacent nodes.
If the adjacent node is not visited before or a cheaper cost is found, update its cost in prices[].
Push the updated node and its cost into the queue for further traversal.
Decrease k after processing one complete BFS level.
Return prices[dst] as the final answer. If it remains -1, then no valid path exists.
C++
#include<iostream>usingnamespacestd;// Function to find the minimum cost// from src to dst with at most k stopsintfindCheapestCost(intn,vector<vector<int>>&edges,intsrc,intdst,intk){//if the destination cannot be reachedif(dst>n)return-1;// Increase k by 1 Because on reaching// destination, k becomes k+1k=k+1;// Making Adjacency Listvector<pair<int,int>>adj[n];// U->{v, wt}for(autoit:edges){adj[it[0]].push_back({it[1],it[2]});}// Vector for Storing pricesvector<int>prices(n,-1);// Queue for storing vertex and costqueue<pair<int,int>>q;q.push({src,0});prices[src]=0;while(!q.empty()){// If all the k stops are used,// then breakif(k==0)break;intsz=q.size();while(sz--){intnode=q.front().first;intcost=q.front().second;q.pop();for(autoit:adj[node]){if(prices[it.first]==-1orcost+it.second<prices[it.first]){prices[it.first]=cost+it.second;q.push({it.first,cost+it.second});}}}k--;}returnprices[dst];}intmain(){intn=6;vector<vector<int>>edges={{0,1,10},{1,2,20},{2,5,30},{1,3,10},{3,4,10},{4,5,10}};intsrc=0;intdst=5;intk=2;cout<<findCheapestCost(n,edges,src,dst,k)<<endl;return0;}
Java
importjava.util.*;publicclassGFG{// Function to find the minimum cost// from src to dst with at most k stopsstaticintfindCheapestCost(intn,int[][]edges,intsrc,intdst,intk){// if the destination cannot be reachedif(dst>=n)return-1;// Increase k by 1 Because on reaching// destination, k becomes k+1k=k+1;// Making Adjacency ListArrayList<ArrayList<int[]>>adj=newArrayList<>();for(inti=0;i<n;i++){adj.add(newArrayList<>());}// U->{v, wt}for(int[]it:edges){adj.get(it[0]).add(newint[]{it[1],it[2]});}// Array for storing pricesint[]prices=newint[n];Arrays.fill(prices,-1);// Queue for storing vertex and costQueue<int[]>q=newLinkedList<>();q.offer(newint[]{src,0});prices[src]=0;while(!q.isEmpty()){// If all the k stops are used,// then breakif(k==0)break;intsz=q.size();while(sz-->0){int[]curr=q.poll();intnode=curr[0];intcost=curr[1];for(int[]it:adj.get(node)){if(prices[it[0]]==-1||cost+it[1]<prices[it[0]]){prices[it[0]]=cost+it[1];q.offer(newint[]{it[0],cost+it[1]});}}}k--;}returnprices[dst];}publicstaticvoidmain(String[]args){intn=6;int[][]edges={{0,1,10},{1,2,20},{2,5,30},{1,3,10},{3,4,10},{4,5,10}};intsrc=0;intdst=5;intk=2;System.out.println(findCheapestCost(n,edges,src,dst,k));}}
Python
fromcollectionsimportdeque# Function to find the minimum cost# from src to dst with at most k stopsdeffindCheapestCost(n,edges,src,dst,k):# if the destination cannot be reachedifdst>n:return-1;# Increase k by 1 Because on reaching# destination, k becomes k+1k=k+1# Making Adjacency Listadj=[[]for_inrange(n)]# U->{v, wt}foritinedges:adj[it[0]].append([it[1],it[2]])# Vector for Storing pricesprices=[-1for_inrange(n)]# Queue for storing vertex and costq=deque()q.append([src,0])prices[src]=0while(len(q)!=0):# If all the k stops are used,# then breakif(k==0):breaksz=len(q)while(True):sz-=1pr=q.popleft()node=pr[0]cost=pr[1]foritinadj[node]:if(prices[it[0]]==-1orcost+it[1]<prices[it[0]]):prices[it[0]]=cost+it[1]q.append([it[0],cost+it[1]])ifsz==0:breakk-=1returnprices[dst]if__name__=="__main__":n=6edges=[[0,1,10],[1,2,20],[2,5,30],[1,3,10],[3,4,10],[4,5,10]]src=0dst=5k=2print(findCheapestCost(n,edges,src,dst,k))# This code is contributed by rakeshsahni
C#
usingSystem;usingSystem.Collections.Generic;classProgram{// Function to find the minimum cost// from src to dst with at most k stopspublicstaticintfindCheapestCost(intn,int[][]edges,intsrc,intdst,intk){// if the destination cannot be reachedif(dst>n){return-1;}// Increase k by 1 Because on reaching// destination, k becomes k+1k=k+1;// Making Adjacency ListList<List<int[]>>adj=newList<List<int[]>>();for(inti=0;i<n;i++){adj.Add(newList<int[]>());}// U->{v, wt}foreach(int[]itinedges){adj[it[0]].Add(newint[]{it[1],it[2]});}// Vector for Storing pricesint[]prices=newint[n];for(inti=0;i<n;i++){prices[i]=-1;}// Queue for storing vertex and costQueue<int[]>q=newQueue<int[]>();q.Enqueue(newint[]{src,0});prices[src]=0;while(q.Count!=0){// If all the k stops are used,// then breakif(k==0){break;}intsz=q.Count;while(sz-->0){int[]pr=q.Dequeue();intnode=pr[0];intcost=pr[1];foreach(int[]itinadj[node]){if(prices[it[0]]==-1||cost+it[1]<prices[it[0]]){prices[it[0]]=cost+it[1];q.Enqueue(newint[]{it[0],cost+it[1]});}}}k--;}returnprices[dst];}publicstaticvoidMain(){intn=6;int[][]edges={newint[]{0,1,10},newint[]{1,2,20},newint[]{2,5,30},newint[]{1,3,10},newint[]{3,4,10},newint[]{4,5,10}};intsrc=0;intdst=5;intk=2;Console.WriteLine(findCheapestCost(n,edges,src,dst,k));}}
JavaScript
functionfindCheapestCost(n,edges,src,dst,k){// if the destination cannot be reachedif(dst>n){return-1;}// Increase k by 1 Because on reaching// destination, k becomes k+1k=k+1;// Making Adjacency Listletadj=Array.from({length:n},()=>[]);for(leti=0;i<edges.length;i++){adj[edges[i][0]].push([edges[i][1],edges[i][2]]);}// Vector for Storing pricesletprices=Array.from({length:n},()=>-1);// Queue for storing vertex and costletq=[];q.push([src,0]);prices[src]=0;while(q.length!=0){// If all the k stops are used,// then breakif(k==0){break;}letsz=q.length;while(sz>0){sz-=1;letpr=q.shift();letnode=pr[0];letcost=pr[1];for(leti=0;i<adj[node].length;i++){letit=adj[node][i];if(prices[it[0]]==-1||cost+it[1]<prices[it[0]]){prices[it[0]]=cost+it[1];q.push([it[0],cost+it[1]]);}}if(sz==0){break;}}k-=1;}returnprices[dst];}// Driver Codeletn=6;letedges=[[0,1,10],[1,2,20],[2,5,30],[1,3,10],[3,4,10],[4,5,10],];letsrc=0;letdst=5;letk=2;console.log(findCheapestCost(n,edges,src,dst,k));
Output
60
Using Bellman-Ford Relaxation - O(k*E) Time and O(V) Space
The idea is to relax all the edges at most k + 1 times because a path with at most k nodes can contain at most k + 1 edges. For every iteration, we try to minimize the cost to reach each node using the previously computed costs, ensuring that only paths within the allowed number of nodes are considered.
Steps:
Initialize a cost[] array with a very large value and set the source node cost as 0.
Run the loop k + 1 times because at most k nodes means at most k + 1 edges.
In every iteration, create a temporary array curr to store updated minimum costs.
Traverse all edges and relax an edge if a cheaper path to the destination node is found.
After all iterations, return the minimum cost to reach dst; if unreachable, return -1.
C++
#include<iostream>#include<vector>usingnamespacestd;// Function to find the minimum cost// from src to dst with at most k stopsintfindCheapestCost(intn,vector<vector<int>>&edges,intsrc,intdst,intk){constintmaxCost=1000000;// Vector for storing minimum costvector<int>cost(n,maxCost);cost[src]=0;// Relax all edges at most k + 1 timesfor(inti=0;i<=k;i++){vector<int>curr=cost;for(auto&edge:edges){intu=edge[0];intv=edge[1];intwt=edge[2];// If source node is reachableif(cost[u]!=maxCost){// Relax the edgecurr[v]=min(curr[v],cost[u]+wt);}}cost=curr;}// If destination is unreachableif(cost[dst]==maxCost)return-1;returncost[dst];}intmain(){intn=6;vector<vector<int>>edges={{0,1,10},{1,2,20},{2,5,30},{1,3,10},{3,4,10},{4,5,10}};intsrc=0;intdst=5;intk=2;cout<<findCheapestCost(n,edges,src,dst,k)<<endl;return0;}
Java
importjava.util.*;classSolution{// Function to find the minimum cost// from src to dst with at most k stopspublicstaticintfindCheapestCost(intn,int[][]edges,intsrc,intdst,intk){intmaxCost=1000000;// Array for storing minimum costint[]cost=newint[n];Arrays.fill(cost,maxCost);cost[src]=0;// Relax all edges at most k + 1 timesfor(inti=0;i<=k;i++){int[]curr=cost.clone();for(int[]edge:edges){intu=edge[0];intv=edge[1];intwt=edge[2];// If source node is reachableif(cost[u]!=maxCost){// Relax the edgecurr[v]=Math.min(curr[v],cost[u]+wt);}}cost=curr;}// If destination is unreachableif(cost[dst]==maxCost)return-1;returncost[dst];}publicstaticvoidmain(String[]args){intn=6;int[][]edges={{0,1,10},{1,2,20},{2,5,30},{1,3,10},{3,4,10},{4,5,10}};intsrc=0;intdst=5;intk=2;System.out.println(findCheapestCost(n,edges,src,dst,k));}}
Python
# Function to find the minimum cost# from src to dst with at most k stopsdeffindCheapestCost(n,edges,src,dst,k):maxCost=1000000# List for storing minimum costcost=[maxCost]*ncost[src]=0# Relax all edges at most k + 1 timesforiinrange(k+1):curr=cost[:]foredgeinedges:u=edge[0]v=edge[1]wt=edge[2]# If source node is reachableifcost[u]!=maxCost:# Relax the edgecurr[v]=min(curr[v],cost[u]+wt)cost=curr# If destination is unreachableifcost[dst]==maxCost:return-1returncost[dst]n=6edges=[[0,1,10],[1,2,20],[2,5,30],[1,3,10],[3,4,10],[4,5,10]]src=0dst=5k=2print(findCheapestCost(n,edges,src,dst,k))
C#
usingSystem;classProgram{// Function to find the minimum cost// from src to dst with at most k stopspublicstaticintfindCheapestCost(intn,int[][]edges,intsrc,intdst,intk){intmaxCost=1000000;// Array for storing minimum costint[]cost=newint[n];for(inti=0;i<n;i++){cost[i]=maxCost;}cost[src]=0;// Relax all edges at most k + 1 timesfor(inti=0;i<=k;i++){int[]curr=(int[])cost.Clone();foreach(int[]edgeinedges){intu=edge[0];intv=edge[1];intwt=edge[2];// If source node is reachableif(cost[u]!=maxCost){// Relax the edgecurr[v]=Math.Min(curr[v],cost[u]+wt);}}cost=curr;}// If destination is unreachableif(cost[dst]==maxCost)return-1;returncost[dst];}staticvoidMain(){intn=6;int[][]edges={newint[]{0,1,10},newint[]{1,2,20},newint[]{2,5,30},newint[]{1,3,10},newint[]{3,4,10},newint[]{4,5,10}};intsrc=0;intdst=5;intk=2;Console.WriteLine(findCheapestCost(n,edges,src,dst,k));}}
JavaScript
// Function to find the minimum cost// from src to dst with at most k stopsfunctionfindCheapestCost(n,edges,src,dst,k){constmaxCost=1000000;// Array for storing minimum costletcost=newArray(n).fill(maxCost);cost[src]=0;// Relax all edges at most k + 1 timesfor(leti=0;i<=k;i++){letcurr=[...cost];for(letedgeofedges){letu=edge[0];letv=edge[1];letwt=edge[2];// If source node is reachableif(cost[u]!=maxCost){// Relax the edgecurr[v]=Math.min(curr[v],cost[u]+wt);}}cost=curr;}// If destination is unreachableif(cost[dst]==maxCost)return-1;returncost[dst];}letn=6;letedges=[[0,1,10],[1,2,20],[2,5,30],[1,3,10],[3,4,10],[4,5,10]];letsrc=0;letdst=5;letk=2;console.log(findCheapestCost(n,edges,src,dst,k));