Open In App

Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph

Last Updated : 21 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a directed graph, which may contain cycles, where every edge has weight, the task is to find the minimum cost of any simple path from a given source vertex ‘s’ to a given destination vertex ‘t’. Simple Path is the path from one vertex to another such that no vertex is visited more than once. If there is no simple path possible then return INF(infinite).

The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j.

Examples:

Input : V = 5, E = 6
        s = 0, t = 2
    graph[][] =      0   1   2   3   4  
                 0  INF -1  INF  1  INF
                 1  INF INF -2  INF INF
                 2  -3  INF INF INF INF
                 3  INF INF -1  INF INF
                 4  INF INF INF  2  INF
 
Output : -3 
Explanation : 
The minimum cost simple path between 0 and 2 is given by:
0 -----> 1 ------> 2 whose cost is (-1) + (-2) = (-3). 

Input : V = 5, E = 6
        s = 0, t = 4
    graph[][] =      0   1   2   3   4  
                 0  INF -7  INF -2  INF
                 1  INF INF -11 INF INF
                 2  INF INF INF INF INF
                 3  INF INF INF  3  -4
                 4  INF INF INF INF INF
 
Output : -6
Explanation : 
The minimum cost simple path between 0 and 2 is given by:
0 -----> 3 ------> 4 whose cost is (-2) + (-4) = (-6). 

Approach :
The main idea to solve the above problem is to traverse through all simple paths from s to t using a modified version of Depth First Search and find the minimum cost path amongst them. One important observation about DFS is that it traverses one path at a time, hence we can traverse separate paths independently using DFS by marking the nodes as unvisited before leaving them.
A simple solution is to start from s, go to all adjacent vertices, and follow recursion for further adjacent vertices until we reach the destination. This algorithm will work even when negative weight cycles or self-edges are present in the graph.

Below is the implementation of the above-mentioned approach: 

C++




// C++ code for printing Minimum Cost
// Simple Path between two given nodes
// in a directed and weighted graph
#include <bits/stdc++.h>
using namespace std;
 
// Define number of vertices in
// the graph and infinite value
#define V 5
#define INF INT_MAX
 
// Function to do DFS through the nodes
int minimumCostSimplePath(int u, int destination,
                    bool visited[], int graph[][V])
{
 
    // check if we find the destination
    // then further cost will be 0
    if (u == destination)
        return 0;
 
    // marking the current node as visited
    visited[u] = 1;
 
    int ans = INF;
 
    // traverse through all
    // the adjacent nodes
    for (int i = 0; i < V; i++) {
        if (graph[u][i] != INF && !visited[i]) {
 
            // cost of the further path
            int curr = minimumCostSimplePath(i,
                        destination, visited, graph);
 
            // check if we have reached the destination
            if (curr < INF) {
 
                // Taking the minimum cost path
                ans = min(ans, graph[u][i] + curr);
            }
        }
    }
 
    // unmarking the current node
    // to make it available for other
    // simple paths
    visited[u] = 0;
 
    // returning the minimum cost
    return ans;
}
 
// driver code
int main()
{
 
    // initialising the graph
    int graph[V][V];
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            graph[i][j] = INF;
        }
    }
 
    // marking all nodes as unvisited
    bool visited[V] = { 0 };
 
    // initialising the edges;
    graph[0][1] = -1;
    graph[0][3] = 1;
    graph[1][2] = -2;
    graph[2][0] = -3;
    graph[3][2] = -1;
    graph[4][3] = 2;
 
    // source and destination
    int s = 0, t = 2;
 
    // marking the source as visited
    visited[s] = 1;
 
    cout << minimumCostSimplePath(s, t,
                            visited, graph);
 
    return 0;
}


Java




// Java code for printing Minimum Cost
// Simple Path between two given nodes
// in a directed and weighted graph
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Define number of vertices in
// the graph and infinite value
static int V = 5;
static int INF = Integer.MAX_VALUE;
 
// Function to do DFS through the nodes
static int minimumCostSimplePath(int u, int destination,
                                 boolean visited[],
                                 int graph[][])
{
     
    // Check if we find the destination
    // then further cost will be 0
    if (u == destination)
        return 0;
         
    // Marking the current node as visited
    visited[u] = true;
 
    int ans = INF;
 
    // Traverse through all
    // the adjacent nodes
    for(int i = 0; i < V; i++)
    {
        if (graph[u][i] != INF && !visited[i])
        {
             
            // Cost of the further path
            int curr = minimumCostSimplePath(i,
                        destination, visited, graph);
 
            // Check if we have reached the
            // destination
            if (curr < INF)
            {
                 
                // Taking the minimum cost path
                ans = Math.min(ans, graph[u][i] + curr);
            }
        }
    }
 
    // Unmarking the current node
    // to make it available for other
    // simple paths
    visited[u] = false;
 
    // Returning the minimum cost
    return ans;
}  
 
// Driver code
public static void main(String[] args)
{
     
    // Initialising the graph
    int graph[][] = new int[V][V];
    for(int i = 0; i < V; i++)
    {
        for(int j = 0; j < V; j++)
        {
            graph[i][j] = INF;
        }
    }
     
    // Marking all nodes as unvisited
    boolean visited[] = new boolean[V];
     
    // Initialising the edges;
    graph[0][1] = -1;
    graph[0][3] = 1;
    graph[1][2] = -2;
    graph[2][0] = -3;
    graph[3][2] = -1;
    graph[4][3] = 2;
     
    // Source and destination
    int s = 0, t = 2;
     
    // Marking the source as visited
    visited[s] = true;
     
    System.out.println(minimumCostSimplePath(s, t,
                            visited, graph));
}
}
 
// This code is contributed by offbeat


Python3




# Python3 code for printing Minimum Cost
# Simple Path between two given nodes
# in a directed and weighted graph
import sys
 
V = 5
INF = sys.maxsize
  
# Function to do DFS through the nodes
def minimumCostSimplePath(u, destination,
                          visited, graph):
 
    # Check if we find the destination
    # then further cost will be 0
    if (u == destination):
        return 0
  
    # Marking the current node as visited
    visited[u] = 1
  
    ans = INF
  
    # Traverse through all
    # the adjacent nodes
    for i in range(V):
        if (graph[u][i] != INF and not visited[i]):
  
            # Cost of the further path
            curr = minimumCostSimplePath(i, destination,
                                         visited, graph)
  
            # Check if we have reached the destination
            if (curr < INF):
  
                # Taking the minimum cost path
                ans = min(ans, graph[u][i] + curr)
             
    # Unmarking the current node
    # to make it available for other
    # simple paths
    visited[u] = 0
  
    # Returning the minimum cost
    return ans
     
# Driver code
if __name__=="__main__":
     
    # Initialising the graph
    graph = [[INF for j in range(V)]
                  for i in range(V)]
  
    # Marking all nodes as unvisited
    visited = [0 for i in range(V)]
  
    # Initialising the edges
    graph[0][1] = -1
    graph[0][3] = 1
    graph[1][2] = -2
    graph[2][0] = -3
    graph[3][2] = -1
    graph[4][3] = 2
     
    # Source and destination
    s = 0
    t = 2
  
    # Marking the source as visited
    visited[s] = 1
     
    print(minimumCostSimplePath(s, t, visited, graph))
  
# This code is contributed by rutvik_56


C#




// C# code for printing Minimum Cost
// Simple Path between two given nodes
// in a directed and weighted graph
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
   
    // Define number of vertices in
    // the graph and infinite value
    static int V = 5;
    static int INF = int.MaxValue;
 
    // Function to do DFS through the nodes
    static int minimumCostSimplePath(int u, int destination,
                                     bool[] visited, int[, ] graph)
    {
       
        // Check if we find the destination
        // then further cost will be 0
        if (u == destination)
            return 0;
 
        // Marking the current node as visited
        visited[u] = true;
        int ans = INF;
 
        // Traverse through all
        // the adjacent nodes
        for (int i = 0; i < V; i++)
        {
            if (graph[u, i] != INF && !visited[i])
            {
               
                // Cost of the further path
                int curr = minimumCostSimplePath(i, destination,
                                                 visited, graph);
 
                // Check if we have reached the
                // destination
                if (curr < INF)
                {
                   
                    // Taking the minimum cost path
                    ans = Math.Min(ans, graph[u, i] + curr);
                }
            }
        }
 
        // Unmarking the current node
        // to make it available for other
        // simple paths
        visited[u] = false;
 
        // Returning the minimum cost
        return ans;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
       
        // Initialising the graph
        int[, ] graph = new int[V, V];
        for (int i = 0; i < V; i++)
        {
            for (int j = 0; j < V; j++)
            {
                graph[i, j] = INF;
            }
        }
 
        // Marking all nodes as unvisited
        bool[] visited = new bool[V];
 
        // Initialising the edges;
        graph[0, 1] = -1;
        graph[0, 3] = 1;
        graph[1, 2] = -2;
        graph[2, 0] = -3;
        graph[3, 2] = -1;
        graph[4, 3] = 2;
 
        // Source and destination
        int s = 0, t = 2;
 
        // Marking the source as visited
        visited[s] = true;
        Console.WriteLine(minimumCostSimplePath(s, t, visited, graph));
    }
}
 
// This code is contributed by sanjeev2552


Javascript




<script>
 
// JavaScript code for printing Minimum Cost
// Simple Path between two given nodes
// in a directed and weighted graph
 
 
// Define number of vertices in
// the graph and infinite value
let V = 5
let INF =  Number.MAX_SAFE_INTEGER
 
// Function to do DFS through the nodes
function minimumCostSimplePath(u, destination, visited, graph)
{
 
    // check if we find the destination
    // then further cost will be 0
    if (u == destination)
        return 0;
 
    // marking the current node as visited
    visited[u] = 1;
 
    let ans = INF;
 
    // traverse through all
    // the adjacent nodes
    for (let i = 0; i < V; i++) {
        if (graph[u][i] != INF && !visited[i]) {
 
            // cost of the further path
            let curr = minimumCostSimplePath(i,
                        destination, visited, graph);
 
            // check if we have reached the destination
            if (curr < INF) {
 
                // Taking the minimum cost path
                ans = Math.min(ans, graph[u][i] + curr);
            }
        }
    }
 
    // unmarking the current node
    // to make it available for other
    // simple paths
    visited[u] = 0;
 
    // returning the minimum cost
    return ans;
}
 
// driver code
 
 
    // initialising the graph
    let graph = new Array();
    for(let i = 0;  i< V; i++){
        graph.push([])
    }
 
    for (let i = 0; i < V; i++) {
        for (let j = 0; j < V; j++) {
            graph[i][j] = INF;
        }
    }
 
    // marking all nodes as unvisited
    let visited = new Array(V).fill(0);
 
    // initialising the edges;
    graph[0][1] = -1;
    graph[0][3] = 1;
    graph[1][2] = -2;
    graph[2][0] = -3;
    graph[3][2] = -1;
    graph[4][3] = 2;
 
    // source and destination
    let s = 0, t = 2;
 
    // marking the source as visited
    visited[s] = 1;
 
    document.write(minimumCostSimplePath(s, t, visited, graph));
 
    // This code is contributed by _saurabh_jaiswal
     
    </script>


Output: 

-3

 

Time Complexity: O(V^2)
Auxiliary Space: O(V), since we are using an array of size V to store the visited nodes.



Previous Article
Next Article

Similar Reads

Minimum cost of path between given nodes containing at most K nodes in a directed and weighted graph
Given a directed weighted graph represented by a 2-D array graph[][] 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, retu
10 min read
Minimum Cost Path in a directed graph via given set of intermediate nodes
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 Output: 11 Explanation: Minimum path 0-&gt;7-&gt;5-&gt;6. Therefore, the cost of the path = 3 + 6 + 2 = 11
10 min read
Shortest path with exactly k edges in a directed and weighted graph
Given a directed and two vertices ‘u’ and ‘v’ in it, find shortest path from ‘u’ to ‘v’ with exactly k edges on the path. The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j. For example, consider the follow
15+ min read
Shortest path with exactly k edges in a directed and weighted graph | Set 2
Given a directed weighted graph and two vertices S and D in it, the task is to find the shortest path from S to D with exactly K edges on the path. If no such path exists, print -1. Examples: Input: N = 3, K = 2, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 8 Explanation: The shortest path with two edges will be 1-&gt;2-&gt;3
8 min read
Monotonic shortest path from source to destination in Directed Weighted Graph
Given a weighted directed graph with N vertices and M edges, a source src and a destination target, the task is to find the shortest monotonic path (monotonically increasing or decreasing) from the source to the destination. Output -1 if no monotonic path is possible. Note: All weights are non-negative Examples: Input: N = 6, M = 9, src = 1, target
14 min read
What is Directed Graph? | Directed Graph meaning
A directed graph is defined as a type of graph where the edges have a direction associated with them. Characteristics of Directed Graph Directed graphs have several characteristics that make them different from undirected graphs. Here are some key characteristics of directed graphs: Directed edges: In a directed graph, edges have a direction associ
3 min read
Number of distinct Shortest Paths from Node 1 to N in a Weighted and Directed Graph
Given a directed and weighted graph of N nodes and M edges, the task is to count the number of shortest length paths between node 1 to N. Examples: Input: N = 4, M = 5, edges = {{1, 4, 5}, {1, 2, 4}, {2, 4, 5}, {1, 3, 2}, {3, 4, 3}}Output: 2Explanation: The number of shortest path from node 1 to node 4 is 2, having cost 5. Input: N = 3, M = 2, edge
10 min read
Convert the undirected graph into directed graph such that there is no path of length greater than 1
Given an undirected graph with N vertices and M edges and no self loops or multiple edges. The task is to convert the given undirected graph into a directed graph such that there is no path of length greater than 1. If it is possible to make such a graph then print two space-separated integers u and v in M lines where u, v denotes source and destin
10 min read
Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: Naive Approach: A simple solution is to traverse the whole tree for each query and find the path between the two nodes.Efficient Approach: The idea i
15 min read
Find if there is a path between two vertices in a directed graph
Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: Consider the following Graph: Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -&gt; 2 -&gt; 3 Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 Approach: Either Bread
15 min read