VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-cost-path-in-a-directed-graph-via-given-set-of-intermediate-nodes/

⇱ Minimum Cost Path in a directed graph via given set of intermediate nodes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Cost Path in a directed graph via given set of intermediate nodes

Last Updated : 15 Jul, 2025

Given a weighted, directed graph G, an array V[] consisting of vertices, the task is to find the Minimum Cost Path passing through all the vertices of the set V, from a given source S to a destination D.

Examples: 

Input: V = {7}, S = 0, D = 6 
 

👁 Image


Output: 11 
Explanation: 
Minimum path 0->7->5->6. 
Therefore, the cost of the path = 3 + 6 + 2 = 11

Input: V = {7, 4}, S = 0, D = 6 
 

👁 Image


Output: 12 
Explanation: 
Minimum path 0->7->4->6. 
Therefore the cost of the path = 3 + 5 + 4 = 12 

Approach: 
To solve the problem, the idea is to use Breadth-First-Search traversal. BFS is generally used to find the Shortest Paths in the graph and the minimum distance of all nodes from Source, intermediate nodes, and Destination can be calculated by the BFS from these nodes.

Follow the steps below to solve the problem:  

  • Initialize minSum to INT_MAX.
  • Traverse the graph from the source node S using BFS.
  • Mark each neighbouring node of the source as the new source and perform BFS from that node.
  • Once the destination node D is encountered, then check if all the intermediate nodes are visited or not.
  • If all the intermediate nodes are visited, then update the minSum and return the minimum value.
  • If all the intermediate nodes are not visited, then return minSum.
  • Mark the source as unvisited.
  • Print the final value of minSum obtained.

Below is the implementation of the above approach:


Output: 
12

 

Time Complexity: O(N*M) 
Auxiliary Space: O(N+M)
 


 

Comment