Minimum cost of path between given nodes containing at most K nodes in a directed and weighted graph
Last Updated : 3 Oct, 2025
Given a directed weighted graph represented by a 2-D arraygraph[][] of size n and 3 integers src, dst, and k representing the source point, destination point, and the available number of stops. The task is to minimize the cost of the path between two nodes containing at most K nodes in a directed and weighted graph. If there is no such route, return -1.
There can be a route marked with a green arrow that takes cost = 10+10+10+10=40 using three stops. And route marked with red arrow takes cost = 10+20+30=60 using two stops. But since there can be at most 2 stops, the answer will be 60.
Since the k is 1, then the green-colored path can be taken with a minimum cost of 20.
Approach: Increase k by 1 because on reaching the destination, k+1 stops will be consumed. Use Breadth-first search to run while loop till the queue becomes empty. At each time pop out all the elements from the queue and decrease k by 1 and check-in their adjacent list of elements and check they are not visited before or their cost is greater than the cost of parent node + cost of that node, then mark their prices by prices[parent] + cost of that node. If k becomes 0 then break the while loop because either cost is calculated or we consumed k+1 stops. Follow the steps below to solve the problem:
Initialize the variables node as the first value of the front pair of the queue and cost as the second value of the front pair of the queue.
Iterate over the range[0, adj[node].size()) using the variable it and perform the following tasks:
If prices[it.first] equals -1 or cost + it.second is less than prices[it.first] then set the value of prices[it.first] as cost + it.second and push the pair {it.first, cost + it.second} into the queue.
Reduce the value of k by 1.
After performing the above steps, print the value of prices[dst] as the answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include<bits/stdc++.h>usingnamespacestd;// Function to find the minimum cost// from src to dst with at most k stopsintfindCheapestCost(intn,vector<vector<int>>&graph,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:graph){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];}// Driver Codeintmain(){intn=6;vector<vector<int>>graph={{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,graph,src,dst,k)<<endl;return0;}
Java
// Java program for the above approachimportjava.util.*;publicclassGFG{staticclasspair{intfirst,second;publicpair(intfirst,intsecond){this.first=first;this.second=second;}}// Function to find the minimum cost// from src to dst with at most k stopsstaticintfindCheapestCost(intn,int[][]graph,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>[]adj=newVector[n];for(inti=0;i<adj.length;i++)adj[i]=newVector<pair>();// U.{v, wt}for(intit[]:graph){adj[it[0]].add(newpair(it[1],it[2]));}// Vector for Storing pricesint[]prices=newint[n];Arrays.fill(prices,-1);// Queue for storing vertex and costQueue<pair>q=newLinkedList<>();q.add(newpair(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){intnode=q.peek().first;intcost=q.peek().second;q.remove();for(pairit:adj[node]){if(prices[it.first]==-1||cost+it.second<prices[it.first]){prices[it.first]=cost+it.second;q.add(newpair(it.first,cost+it.second));}}}k--;}returnprices[dst];}// Driver Codepublicstaticvoidmain(String[]args){intn=6;int[][]graph={{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.print(findCheapestCost(n,graph,src,dst,k)+"\n");}}// This code is contributed by 29AjayKumar
Python3
# python3 program for the above approachfromcollectionsimportdeque# Function to find the minimum cost# from src to dst with at most k stopsdeffindCheapestCost(n,graph,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}foritingraph: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]# Driver Codeif__name__=="__main__":n=6graph=[[0,1,10],[1,2,20],[2,5,30],[1,3,10],[3,4,10],[4,5,10]]src=0dst=5k=2print(findCheapestCost(n,graph,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[,]graph,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}for(inti=0;i<graph.GetLength(0);i++){adj[graph[i,0]].Add(newint[]{graph[i,1],graph[i,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[,]graph={{0,1,10},{1,2,20},{2,5,30},{1,3,10},{3,4,10},{4,5,10}};intsrc=0;intdst=5;intk=2;Console.WriteLine(findCheapestCost(n,graph,src,dst,k));}}
JavaScript
functionfindCheapestCost(n,graph,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<graph.length;i++){adj[graph[i][0]].push([graph[i][1],graph[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];}letn=6;letgraph=[[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,graph,src,dst,k));