Given a Graph consisting of **N** vertices and **M** weighted edges and an array **edges[][]**, with each row representing the two vertices connected by the edge and the weight of the edge, the task is to find the path with the least sum of weights from a given source vertex **src **to a given destination vertex **dst**, made up of **K** intermediate vertices. If no such path exists, then print **-1**.

**Examples:**

Input:N = 3, M = 3, src = 0, dst = 2, K = 1, edges[] = {{0, 1, 100}, {1, 2, 100}, {0, 2, 500}}Output:200Explanation:The path 0 -> 1 -> 2 is the least weighted sum (= 100 + 100 = 200) path connecting src (= 0) and dst(= 2) with exactly K (= 1) intermediate vertex.

Input:N = 3, M = 3, src = 0, dst = 2, K = 0, edges[] = { { 0, 1, 100 }, { 1, 2, 100 }, { 0, 2, 500 } }Output:500Explanation:The direct edge 0 -> 2 with weight 500 is the required path.

**Approach: **The given problem can be solved using Priority Queue and perform BFS. Follow the steps below to solve this problem:

- Initialize a priority queue to store the tuples
**{cost to reach this vertex, vertex, number of stops}**. - Push
**{0, src, k+1}**as the first starting point. - Pop-out the top element of priority queue. If all stops are exhausted, then repeat this step.
- If the destination is reached, then print
**the cost to reach the current vertex.** - Otherwise, find the neighbor of this vertex which required the smallest cost to reach that vertex. Push it into the
**priority queue****.** - Repeat from step
**2**. - If no path is found after performing the above steps, print
**-1**.

Below is the implementation of the above approach:

## C++

`// C++ program for the above approach` `#include <bits/stdc++.h>` `using` `namespace` `std;` `// Function to find the minimum cost path` `// from the source vertex to destination` `// vertex via K intermediate vertices` `int` `leastWeightedSumPath(` `int` `n,` ` ` `vector<vector<` `int` `> >& edges,` ` ` `int` `src, ` `int` `dst, ` `int` `K)` `{` ` ` `// Initialize the adjacency list` ` ` `unordered_map<` `int` `,` ` ` `vector<pair<` `int` `, ` `int` `> > >` ` ` `graph;` ` ` `// Generate the adjacency list` ` ` `for` `(vector<` `int` `>& edge : edges) {` ` ` `graph[edge[0]].push_back(` ` ` `make_pair(edge[1], edge[2]));` ` ` `}` ` ` `// Initialize the minimum priority queue` ` ` `priority_queue<vector<` `int` `>, vector<vector<` `int` `> >,` ` ` `greater<vector<` `int` `> > >` ` ` `pq;` ` ` `// Stores the minimum cost to` ` ` `// travel between vertices via` ` ` `// K intermediate nodes` ` ` `vector<vector<` `int` `> > costs(n,` ` ` `vector<` `int` `>(` ` ` `K + 2, INT_MAX));` ` ` `costs[src][K + 1] = 0;` ` ` `// Push the starting vertex,` ` ` `// cost to reach and the number` ` ` `// of remaining vertices` ` ` `pq.push({ 0, src, K + 1 });` ` ` `while` `(!pq.empty()) {` ` ` `// Pop the top element` ` ` `// of the stack` ` ` `auto` `top = pq.top();` ` ` `pq.pop();` ` ` `// If destination is reached` ` ` `if` `(top[1] == dst)` ` ` `// Return the cost` ` ` `return` `top[0];` ` ` `// If all stops are exhausted` ` ` `if` `(top[2] == 0)` ` ` `continue` `;` ` ` `// Find the neighbour with minimum cost` ` ` `for` `(` `auto` `neighbor : graph[top[1]]) {` ` ` `// Pruning` ` ` `if` `(costs[neighbor.first][top[2] - 1]` ` ` `< neighbor.second + top[0]) {` ` ` `continue` `;` ` ` `}` ` ` `// Update cost` ` ` `costs[neighbor.first][top[2] - 1]` ` ` `= neighbor.second + top[0];` ` ` `// Update priority queue` ` ` `pq.push({ neighbor.second + top[0],` ` ` `neighbor.first, top[2] - 1 });` ` ` `}` ` ` `}` ` ` `// If no path exists` ` ` `return` `-1;` `}` `// Driver Code` `int` `main()` `{` ` ` `int` `n = 3, src = 0, dst = 2, k = 1;` ` ` `vector<vector<` `int` `> > edges` ` ` `= { { 0, 1, 100 },` ` ` `{ 1, 2, 100 },` ` ` `{ 0, 2, 500 } };` ` ` `// Function Call to find the path` ` ` `// from src to dist via k nodes` ` ` `// having least sum of weights` ` ` `cout << leastWeightedSumPath(n, edges,` ` ` `src, dst, k);` ` ` `return` `0;` `}` |

## Python3

`# Python3 program for the above approach` `# Function to find the minimum cost path` `# from the source vertex to destination` `# vertex via K intermediate vertices` `def` `leastWeightedSumPath(n, edges, src, dst, K):` ` ` `graph ` `=` `[[] ` `for` `i ` `in` `range` `(` `3` `)]` ` ` `# Generate the adjacency list` ` ` `for` `edge ` `in` `edges:` ` ` `graph[edge[` `0` `]].append([edge[` `1` `], edge[` `2` `]])` ` ` `# Initialize the minimum priority queue` ` ` `pq ` `=` `[]` ` ` `# Stores the minimum cost to` ` ` `# travel between vertices via` ` ` `# K intermediate nodes` ` ` `costs ` `=` `[[` `10` `*` `*` `9` `for` `i ` `in` `range` `(K ` `+` `2` `)] ` `for` `i ` `in` `range` `(n)]` ` ` `costs[src][K ` `+` `1` `] ` `=` `0` ` ` `# Push the starting vertex,` ` ` `# cost to reach and the number` ` ` `# of remaining vertices` ` ` `pq.append([ ` `0` `, src, K ` `+` `1` `])` ` ` `pq ` `=` `sorted` `(pq)[::` `-` `1` `]` ` ` `while` `(` `len` `(pq) > ` `0` `):` ` ` ` ` `# Pop the top element` ` ` `# of the stack` ` ` `top ` `=` `pq[` `-` `1` `]` ` ` `del` `pq[` `-` `1` `]` ` ` `# If destination is reached` ` ` `if` `(top[` `1` `] ` `=` `=` `dst):` ` ` ` ` `# Return the cost` ` ` `return` `top[` `0` `]` ` ` `# If all stops are exhausted` ` ` `if` `(top[` `2` `] ` `=` `=` `0` `):` ` ` `continue` ` ` `# Find the neighbour with minimum cost` ` ` `for` `neighbor ` `in` `graph[top[` `1` `]]:` ` ` `# Pruning` ` ` `if` `(costs[neighbor[` `0` `]][top[` `2` `] ` `-` `1` `] < neighbor[` `1` `] ` `+` `top[` `0` `]):` ` ` `continue` ` ` `# Update cost` ` ` `costs[neighbor[` `0` `]][top[` `2` `] ` `-` `1` `] ` `=` `neighbor[` `1` `]` `+` `top[` `0` `]` ` ` `# Update priority queue` ` ` `pq.append([neighbor[` `1` `]` `+` `top[` `0` `],neighbor[` `0` `], top[` `2` `] ` `-` `1` `])` ` ` `pq ` `=` `sorted` `(pq)[::` `-` `1` `]` ` ` `# If no path exists` ` ` `return` `-` `1` `# Driver Code` `if` `__name__ ` `=` `=` `'__main__'` `:` ` ` `n, src, dst, k ` `=` `3` `, ` `0` `, ` `2` `, ` `1` ` ` `edges ` `=` `[ [ ` `0` `, ` `1` `, ` `100` `],` ` ` `[ ` `1` `, ` `2` `, ` `100` `],` ` ` `[ ` `0` `, ` `2` `, ` `500` `] ]` ` ` `# Function Call to find the path` ` ` `# from src to dist via k nodes` ` ` `# having least sum of weights` ` ` `print` `(leastWeightedSumPath(n, edges, src, dst, k))` `# This code is contributed by mohit kumar 29.` |

**Output:**

200

**Time Complexity : **O(N * log N) **Auxiliary Space**: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course****.**

In case you wish to attend live classes with industry experts, please refer **Geeks Classes Live**