The Wayback Machine - https://web.archive.org/web/20240817145907/https://www.geeksforgeeks.org/maximum-cost-path-from-source-node-to-destination-node-via-at-most-k-intermediate-nodes/
Open In App

Maximum cost path from source node to destination node via at most K intermediate nodes

Last Updated : 12 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Examples:

Input: N = 3, Edges[][] = {{0, 1, 100}, {1, 2, 100}, {0, 2, 500}}, src = 0, dst = 2, K = 0
Output: 500
Explanation:
 

Path 0 → 2: The path with maximum weight and at most 0 intermediate nodes is of weight 500.

 

Approach: The given problem can be solved by using BFS(Breadth-First Search) Traversal. Follow the steps below to solve the problem:

  • Initialize the variable, say ans, to store the maximum distance between the source and the destination node having at most K intermediates nodes.
  • Initialize an adjacency list of the graph using the edges.
  • Initialize an empty queue and push the source vertex into it. Initialize a variable, say lvl, to store the number of nodes present in between src and dst.
  • While the queue is not empty and lvl is less than K + 2 perform the following steps:
    • Store the size of the queue in a variable, say S.
    • Iterate over the range [1, S] and perform the following steps:
      • Pop the front element of the queue and store it in a variable, say T.
      • If T is the dst vertex, then update the value of ans as the maximum of ans and the current distance T.second.
      • Traverse through all the neighbors of the current popped node and check if the distance of its neighbor is greater than the current distance or not. If found to be true, then push it in the queue and update its distance.
    • Increase the value of lvl by 1.
  • After completing the above steps, print the value of ans as the resultant maximum distance.

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 longest distance
// from source to destination with at
// most K intermediate nodes
int findShortestPath(
    int n, vector<vector<int> >& edges,
    int src, int dst, int K)
{
    // Initialize the adjacency list
    vector<vector<pair<int, int> > > adjlist(
        n, vector<pair<int, int> >());
 
    // Initialize a queue to perform BFS
    queue<pair<int, int> > q;
 
    unordered_map<int, int> mp;
 
    // Store the maximum distance of
    // every node from source vertex
    int ans = INT_MIN;
 
    // Initialize adjacency list
    for (int i = 0; i < edges.size(); i++) {
 
        auto edge = edges[i];
 
        adjlist[edge[0]].push_back(
            make_pair(edge[1], edge[2]));
    }
 
    // Push the first element into queue
    q.push({ src, 0 });
 
    int level = 0;
 
    // Iterate until the queue becomes empty
    // and the number of nodes between src
    // and dst vertex is at most to K
    while (!q.empty() && level < K + 2) {
 
        // Current size of the queue
        int sz = q.size();
 
        for (int i = 0; i < sz; i++) {
 
            // Extract the front
            // element of the queue
            auto pr = q.front();
 
            // Pop the front element
            // of the queue
            q.pop();
 
            // If the dst vertex is reached
            if (pr.first == dst)
                ans = max(ans, pr.second);
 
            // Traverse the adjacent nodes
            for (auto pr2 : adjlist[pr.first]) {
 
                // If the distance is greater
                // than the current distance
                if (mp.find(pr2.first)
                        == mp.end()
                    || mp[pr2.first]
                           > pr.second
                                 + pr2.second) {
 
                    // Push it into the queue
                    q.push({ pr2.first,
                             pr.second
                                 + pr2.second });
                    mp[pr2.first] = pr.second
                                    + pr2.second;
                }
            }
        }
 
        // Increment the level by 1
        level++;
    }
 
    // Finally, return the maximum distance
    return ans != INT_MIN ? ans : -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 } };
 
    cout << findShortestPath(n, edges,
                             src, dst, k);
 
    return 0;
}


Java




import java.util.*;
 
class Main {
 
    // Function to find the longest distance
    // from source to destination with at
    // most K intermediate nodes
    public static int findShortestPath(int n, int[][] edges,
                                       int src, int dst,
                                       int K)
    {
        // Initialize the adjacency list
        List<List<int[]> > adjlist = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adjlist.add(new ArrayList<int[]>());
        }
 
        // Initialize a queue to perform BFS
        Queue<int[]> q = new LinkedList<>();
 
        Map<Integer, Integer> mp = new HashMap<>();
 
        // Store the maximum distance of
        // every node from source vertex
        int ans = Integer.MIN_VALUE;
 
        // Initialize adjacency list
        for (int[] edge : edges) {
            adjlist.get(edge[0]).add(
                new int[] { edge[1], edge[2] });
        }
 
        // Push the first element into queue
        q.add(new int[] { src, 0 });
 
        int level = 0;
 
        // Iterate until the queue becomes empty
        // and the number of nodes between src
        // and dst vertex is at most to K
        while (!q.isEmpty() && level < K + 2) {
 
            // Current size of the queue
            int sz = q.size();
 
            for (int i = 0; i < sz; i++) {
 
                // Extract the front
                // element of the queue
                int[] pr = q.poll();
 
                // If the dst vertex is reached
                if (pr[0] == dst)
                    ans = Math.max(ans, pr[1]);
 
                // Traverse the adjacent nodes
                for (int[] pr2 : adjlist.get(pr[0])) {
 
                    // If the distance is greater
                    // than the current distance
                    if (!mp.containsKey(pr2[0])
                        || mp.get(pr2[0])
                               > pr[1] + pr2[1]) {
 
                        // Push it into the queue
                        q.add(new int[] { pr2[0],
                                          pr[1] + pr2[1] });
                        mp.put(pr2[0], pr[1] + pr2[1]);
                    }
                }
            }
 
            // Increment the level by 1
            level++;
        }
 
        // Finally, return the maximum distance
        return ans != Integer.MIN_VALUE ? ans : -1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 3, src = 0, dst = 2, k = 1;
        int[][] edges = { { 0, 1, 100 },
                          { 1, 2, 100 },
                          { 0, 2, 500 } };
 
        System.out.println(
            findShortestPath(n, edges, src, dst, k));
    }
}


Python3




# Python3 program for the above approach
from collections import deque
 
# Function to find the longest distance
# from source to destination with at
# most K intermediate nodes
def findShortestPath(n, edges, src, dst, K):
     
    # Initialize the adjacency list
    adjlist = [[] for i in range(n)]
     
    # Initialize a queue to perform BFS
    q = deque()
 
    mp = {}
 
    # Store the maximum distance of
    # every node from source vertex
    ans = -10**9
 
    # Initialize adjacency list
    for i in range(len(edges)):
        edge = edges[i]
        adjlist[edge[0]].append([edge[1],
                                 edge[2]])
 
    # Push the first element into queue
    q.append([src, 0])
 
    level = 0
 
    # Iterate until the queue becomes empty
    # and the number of nodes between src
    # and dst vertex is at most to K
    while (len(q) > 0 and level < K + 2):
 
        # Current size of the queue
        sz = len(q)
 
        for i in range(sz):
             
            # Extract the front
            # element of the queue
            pr = q.popleft()
             
            # Pop the front element
            # of the queue
            # q.pop()
 
            # If the dst vertex is reached
            if (pr[0] == dst):
                ans = max(ans, pr[1])
 
            # Traverse the adjacent nodes
            for pr2 in adjlist[pr[0]]:
                 
                # If the distance is greater
                # than the current distance
                if ((pr2[0] not in mp) or
                  mp[pr2[0]] > pr[1] + pr2[1]):
                       
                    # Push it into the queue
                    q.append([pr2[0], pr[1] + pr2[1]])
                    mp[pr2[0]] = pr[1] + pr2[1]
 
        # Increment the level by 1
        level += 1
 
    # Finally, return the maximum distance
    return ans if ans != -10**9 else -1
 
# Driver Code
if __name__ == '__main__':
     
    n, src, dst, k = 3, 0, 2, 1
 
    edges= [ [ 0, 1, 100 ],
             [ 1, 2, 100 ],
             [ 0, 2, 500 ] ]
 
    print(findShortestPath(n, edges,src, dst, k))
 
# This code is contributed by mohit kumar 29


Javascript




// JavaScript implementation of the above C++ code
 
function findShortestPath(n, edges, src, dst, k) {
    // Initialize the adjacency list
    var adjlist = new Array(n).fill(null).map(() => []);
 
    // Initialize a queue to perform BFS
    var q = [];
 
    var mp = new Map();
 
    // Store the maximum distance of
    // every node from source vertex
    var ans = Number.MIN_SAFE_INTEGER;
 
    // Initialize adjacency list
    for (var i = 0; i < edges.length; i++) {
        var edge = edges[i];
        adjlist[edge[0]].push([edge[1], edge[2]]);
    }
 
    // Push the first element into queue
    q.push([src, 0]);
 
    var level = 0;
 
    // Iterate until the queue becomes empty
    // and the number of nodes between src
    // and dst vertex is at most to K
    while (q.length > 0 && level < k + 2) {
        // Current size of the queue
        var sz = q.length;
 
        for (var i = 0; i < sz; i++) {
            // Extract the front
            // element of the queue
            var pr = q.shift();
 
            // If the dst vertex is reached
            if (pr[0] === dst) {
                ans = Math.max(ans, pr[1]);
            }
 
            // Traverse the adjacent nodes
            for (var j = 0; j < adjlist[pr[0]].length; j++) {
                var pr2 = adjlist[pr[0]][j];
 
                // If the distance is greater
                // than the current distance
                if (mp.get(pr2[0]) === undefined || mp.get(pr2[0]) > pr[1] + pr2[1]) {
                    // Push it into the queue
                    q.push([pr2[0], pr[1] + pr2[1]]);
                    mp.set(pr2[0], pr[1] + pr2[1]);
                }
            }
        }
 
        // Increment the level by 1
        level++;
    }
 
    // Finally, return the maximum distance
    return ans !== Number.MIN_SAFE_INTEGER ? ans : -1;
}
 
// Example usage
var n = 3, src = 0, dst = 2, k = 1;
var edges = [[0, 1, 100], [1, 2, 100], [0, 2, 500]];
 
console.log(findShortestPath(n, edges, src, dst, k));


C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG {
    // Function to find the longest distance
    // from source to destination with at
    // most K intermediate nodes
    static int FindShortestPath(int n, int[][] edges, int src, int dst, int K)
    {
        // Initialize the adjacency list
        List<int[]>[] adjlist = new List<int[]>[n];
        for (int i = 0; i < n; i++) {
            adjlist[i] = new List<int[]>();
        }
         
        // Initialize a queue to perform BFS
        Queue<int[]> q = new Queue<int[]>();
 
        Dictionary<int, int> mp = new Dictionary<int, int>();
 
        // Store the maximum distance of
        // every node from source vertex
        int ans = -1000000000;
 
        // Initialize adjacency list
        for (int i = 0; i < edges.Length; i++) {
            int[] edge = edges[i];
            adjlist[edge[0]].Add(new int[] {edge[1], edge[2]});
        }
 
        // Push the first element into queue
        q.Enqueue(new int[] {src, 0});
 
        int level = 0;
 
        // Iterate until the queue becomes empty
        // and the number of nodes between src
        // and dst vertex is at most to K
        while (q.Count > 0 && level < K + 2) {
 
            // Current size of the queue
            int sz = q.Count;
 
            for (int i = 0; i < sz; i++) {
 
                // Extract the front
                // element of the queue
                int[] pr = q.Dequeue();
 
                // If the dst vertex is reached
                if (pr[0] == dst) {
                    ans = Math.Max(ans, pr[1]);
                }
 
                // Traverse the adjacent nodes
                foreach (int[] pr2 in adjlist[pr[0]]) {
 
                    // If the distance is greater
                    // than the current distance
                    if (!mp.ContainsKey(pr2[0]) || mp[pr2[0]] > pr[1] + pr2[1]) {
                        // Push it into the queue
                        q.Enqueue(new int[] {pr2[0], pr[1] + pr2[1]});
                        mp[pr2[0]] = pr[1] + pr2[1];
                    }
                }
            }
 
            // Increment the level by 1
            level++;
        }
 
        // Finally, return the maximum distance
        return ans != -1000000000 ? ans : -1;
    }
 
    // Driver Code
    public static void Main()
    {
        int n = 3, src = 0, dst = 2, k = 1;
 
        int[][] edges = new int[][] {
            new int[] {0, 1, 100},
            new int[] {1, 2, 100},
            new int[] {0, 2, 500}
        };
 
        Console.WriteLine(FindShortestPath(n, edges, src, dst, k));
    }
}
 
 
// This code is contributed by codebraxnzt


Output

500

Time Complexity: O(N + E)
Auxiliary Space: O(N)

Alternate approach: Modification of Bellman Ford algorithm after modifying the weights

If all the weights of the given graph are made negative of the original weights, the path taken to minimize the sum of weights with at most k nodes in middle will give us the path we need. Hence this question is similar to this problem. Below is the code implementation of the problem

C++




#include <bits/stdc++.h>
using namespace std;
 
int max_cost(int n, vector<vector<int> >& edges, int src,
             int dst, int k)
{
    // We use 2 arrays for this algorithm
    // temp is the shortest distances array in current pass
    vector<int> temp(n, INT_MAX);
    temp[src] = 0;
    for (int i = 0; i <= k; i++) {
        // c is the shortest distances array in previous
        // pass For every iteration current pass becomes the
        // previous
        vector<int> c(temp);
        for (auto edge : edges) {
            int a = edge[0], b = edge[1], d = edge[2];
            // Updating the current array using previous
            // array Subtracting d is same as adding -d
            temp[b]
                = min(temp[b],
                      c[a] == INT_MAX ? INT_MAX : c[a] - d);
        }
    }
    // Checking is dst is reachable from src or not
    if (temp[dst] != INT_MAX) {
        // Returning the negative value of the shortest
        // distance to return the longest distance
        return -temp[dst];
    }
    return -1;
}
 
int main()
{
    vector<vector<int> > edges = {
        { 0, 1, 100 },
        { 1, 2, 100 },
        { 0, 2, 500 },
    };
    int src = 0;
    int dst = 2;
    int k = 1;
    int n = 3;
 
    cout << max_cost(n, edges, src, dst, k) << endl;
    return 0;
}
// This code was contributed Prajwal Kandekar


Java




import java.util.*;
 
public class Main {
    static int max_cost(int n, List<List<Integer>> edges, int src,
             int dst, int k)
    {
       
        // We use 2 arrays for this algorithm
        // temp is the shortest distances array in current pass
        int[] temp = new int[n];
        Arrays.fill(temp, Integer.MAX_VALUE);
        temp[src] = 0;
        for (int i = 0; i <= k; i++)
        {
           
            // c is the shortest distances array in previous
            // pass For every iteration current pass becomes the
            // previous
            int[] c = temp.clone();
            for (List<Integer> edge : edges) {
                int a = edge.get(0), b = edge.get(1), d = edge.get(2);
               
                // Updating the current array using previous
                // array Subtracting d is same as adding -d
                temp[b] = Math.min(temp[b], c[a] == Integer.MAX_VALUE ? Integer.MAX_VALUE : c[a] - d);
            }
        }
       
        // Checking if dst is reachable from src or not
        if (temp[dst] != Integer.MAX_VALUE)
        {
           
            // Returning the negative value of the shortest
            // distance to return the longest distance
            return -temp[dst];
        }
        return -1;
    }
 
    public static void main(String[] args) {
        List<List<Integer>> edges = Arrays.asList(
            Arrays.asList(0, 1, 100),
            Arrays.asList(1, 2, 100),
            Arrays.asList(0, 2, 500)
        );
        int src = 0;
        int dst = 2;
        int k = 1;
        int n = 3;
 
        System.out.println(max_cost(n, edges, src, dst, k));
    }
}


Python3




def max_cost(n, edges, src, dst, k):
      # We use 2 arrays for this algorithm
    # temp is the shortest distances array in current pass
    temp=[0 if i==src else float("inf") for i in range(n)]
    for _ in range(k+1):
          # c is the shortest distances array in previous pass
        # For every iteration current pass becomes the previous
        c=temp.copy()
        for a,b,d in edges:
              # Updating the current array using previous array
            # Subtracting d is same as adding -d
            temp[b]=min(temp[b],c[a]-d)
    # Checking is dst is reachable from src or not
    if temp[dst]!=float("inf"):
          # Returning the negative value of the shortest distance to return the longest distance
        return -temp[dst]
    return -1
   
edges = [
    [0, 1, 100],
    [1, 2, 100],
    [0, 2, 500],
]
 
src = 0
dst = 2
k = 1
n = 3
     
print(max_cost(n,edges,src,dst,k))
 
# This code was contributed by Akshayan Muralikrishnan


Javascript




function max_cost(n, edges, src, dst, k) {
    // We use 2 arrays for this algorithm
    // temp is the shortest distances array in current pass
    let temp = new Array(n).fill(Number.MAX_SAFE_INTEGER);
    temp[src] = 0;
 
    for (let i = 0; i <= k; i++) {
        // c is the shortest distances array in previous
        // pass For every iteration current pass becomes the
        // previous
        let c = [...temp];
        for (let j = 0; j < edges.length; j++) {
            let [a, b, d] = edges[j];
            // Updating the current array using previous
            // array Subtracting d is same as adding -d
            temp[b] = Math.min(temp[b], (c[a] === Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : c[a] - d);
        }
    }
 
    // Checking is dst is reachable from src or not
    if (temp[dst] !== Number.MAX_SAFE_INTEGER) {
        // Returning the negative value of the shortest
        // distance to return the longest distance
        return -temp[dst];
    }
    return -1;
}
 
let edges = [    [0, 1, 100],
    [1, 2, 100],
    [0, 2, 500]
];
let src = 0;
let dst = 2;
let k = 1;
let n = 3;
 
console.log(max_cost(n, edges, src, dst, k));


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
public class MainClass
{
    static int MaxCost(int n, List<List<int>> edges, int src, int dst, int k)
    {
 
        // We use 2 arrays for this algorithm
        // temp is the shortest distances array in current pass
        int[] temp = new int[n];
        Array.Fill(temp, int.MaxValue);
        temp[src] = 0;
        for (int i = 0; i <= k; i++)
        {
 
            // c is the shortest distances array in previous
            // pass For every iteration current pass becomes the
            // previous
            int[] c = (int[])temp.Clone();
            foreach (var edge in edges)
            {
                int a = edge[0], b = edge[1], d = edge[2];
 
                // Updating the current array using previous
                // array Subtracting d is same as adding -d
                temp[b] = Math.Min(temp[b], c[a] == int.MaxValue ? int.MaxValue : c[a] - d);
            }
        }
 
        // Checking if dst is reachable from src or not
        if (temp[dst] != int.MaxValue)
        {
 
            // Returning the negative value of the shortest
            // distance to return the longest distance
            return -temp[dst];
        }
        return -1;
    }
 
    public static void Main()
    {
        List<List<int>> edges = new List<List<int>>()
        {
            new List<int>(){0, 1, 100},
            new List<int>(){1, 2, 100},
            new List<int>(){0, 2, 500}
        };
        int src = 0;
        int dst = 2;
        int k = 1;
        int n = 3;
 
        Console.WriteLine(MaxCost(n, edges, src, dst, k));
    }
}


Output

500

Time Complexity: O(E*k) where E is the number of edges
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Minimum cost path from source node to destination node via K intermediate nodes
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
10 min read
Minimum cost path from source node to destination node via an intermediate node
Given an undirected weighted graph. The task is to find the minimum cost of the path from source node to the destination node via an intermediate node. Note: If an edge is traveled twice, only once weight is calculated as cost. Examples: Input: source = 0, destination = 2, intermediate = 3; Output: 6 The minimum cost path 0-&gt;1-&gt;3-&gt;1-&gt;2
12 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
Minimize cost to travel from source to destination in a Matrix based on given row change and column change cost
Given an M*N grid, and given an array startPos[], indicating that the starting position is the cell (startPos[0], startPos[1]) and the array homePos[] indicating its destination is at the cell's (homePos[0], homePos[1]). From any cell movement is allowed only in four directions: left, right, up, and down, and cannot go outside the boundary. There a
7 min read
Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
Given a connected graph with N vertices and M edges. The task is to find the shortest path from source to the destination vertex such that the difference between adjacent edge weights in the shortest path change from positive to negative and vice versa ( Weight(E1) &gt; Weight(E2) &lt; Weight(E3) .... ). If no such path exists then print -1. Exampl
13 min read
Step by step Shortest Path from source node to destination node in a Binary Tree
Given a root of binary tree and two integers startValue and destValue denoting the starting and ending node respectively. The task is to find the shortest path from the start node to the end node and print the path in the form of directions given below. Going from one node to its left child node is indicated by the letter 'L'.Going from one node to
14 min read
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
Source to destination in 2-D path with fixed sized jumps
Given the source point and the destination point of the path and two integers x and y. The task is to check whether it is possible to move from source to the destination with the below moves, If current position is (a, b) then the valid moves are: (a + x, b + y)(a - x, b + y)(a + x, b - y)(a - x, b - y) Examples: Input: Sx = 0, Sy = 0, Dx = 0, Dy =
6 min read
Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
Given a graph with N nodes, a node S and Q queries each consisting of a node D and K, the task is to find the shortest path consisting of exactly K edges from node S to node D for each query. If no such path exists then print -1. Note: K will always be lesser than 2 * N. Examples: Input: N = 3, edges[][] = {{1, 2, 5}, {2, 3, 3}, {3, 1, 4}}, S = 1,
8 min read
Print path from given Source to Destination in 2-D Plane
Given coordinates of a source point (srcx, srcy) and a destination point (dstx, dsty), the task is to determine the possible path to reach the destination point from source point. From any point (x, y) there only two types of valid moves: (2 * x + y, y) or (x, 2 * y + x). If the path doesn't exist then print -1.Examples: Input: (srcx, srcy) = {5, 8
11 min read
Shortest Path with even number of Edges from Source to Destination
Given an undirected graph G, the task is to find the shortest path of even-length, given 1 as Source Node and N as Destination Node. Path length refers to the number of edges present in a path (not the cost of the path). Examples: Input: N = 5, G is given below: Output: 10 Explanation: All paths from 1(source node) to 5 (destination node) are: 1-
13 min read
Queries to check if a path made up of even numbers from source to destination exists in a Matrix
Given two arrays R[] and C[] consisting of N integers such that a matrix of dimensions N x N can be formed whose element at index (i, j) is given by (R[i] + C[j]) for all possible pairs from the two arrays. Given a matrix Queries[][] with each row representing a query of the type {A, B, X, Y}, the task for each query is to check whether there exist
13 min read
Path from a given source to a given destination having Kth largest weight in a Graph
Given a weighted graph consisting of N nodes and M edges, a source vertex, a destination vertex, and an integer K, the task is to find the path with Kth largest weight from source to destination in the graph. Examples: Input: N = 7, M = 8, source = 0, destination = 6, K = 3, Edges[][] = {{0, 1, 10}, {1, 2, 10}, {2, 3, 10}, {0, 3, 40}, {3, 4, 2}, {4
14 min read
Shortest path from a source cell to a destination cell of a Binary Matrix through cells consisting only of 1s
Given a binary matrix mat[][] of dimensions of N * M and pairs of integers src and dest representing source and destination cells respectively, the task is to find the shortest sequence of moves from the given source cell to the destination cell via cells consisting only of 1s. The allowed moves are moving a cell left (L), right (R), up (U), and do
15+ min read
Longest path in a Matrix from a specific source cell to destination cell
Given a matrix mat[][], and the coordinates of source and destination node, the task is to find the length of the longest path from source to destination. Example: Input: mat[][] = {{5, 6, 7, 8}, {4, 1, 0, 9}, {3, 2, 11, 10}}, src = {1, 1}, dest = {2, 2}Output: 11Explanation: The longest path between the coordinates (1, 1) and (2, 2) has 11 nodes a
9 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
Minimum edges to reverse to make path from a source to a destination
Given a directed graph and a source node and destination node, we need to find how many edges we need to reverse in order to make at least 1 path from the source node to the destination node. Examples: In above graph there were two paths from node 0 to node 6, 0 -&gt; 1 -&gt; 2 -&gt; 3 -&gt; 6 0 -&gt; 1 -&gt; 5 -&gt; 4 -&gt; 6 But for first path on
15+ min read
Check whether the cost of going from any node to any other node via all possible paths is same
Given adjacency list representation of a directed graph, the task is to check whether the cost of going from any vertex to any other vertex via all possible paths is equal or not. If there is a cost c for going from vertex A to vertex B, then the cost to travel from vertex B to vertex A will be -c. Examples: Input: arr[][] = {{0, 2, 0, 1}, {-2, 0,
9 min read
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path
Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path. Examples: Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1,
11 min read
Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Number of paths from source to destination in a directed acyclic graph
Given a Directed Acyclic Graph with n vertices and m edges. The task is to find the number of different paths that exist from a source vertex to destination vertex. Examples: Input: source = 0, destination = 4 Output: 3 Explanation: 0 -&gt; 2 -&gt; 3 -&gt; 4 0 -&gt; 3 -&gt; 4 0 -&gt; 4 Input: source = 0, destination = 1 Output: 1 Explanation: There
15+ min read
Number of Walks from source to destination
Given a graph and two vertices src and dest, count the total number of paths from src to dest where the length of the path is k (there should be exactly k edges between them). Note that the graph is represented as an adjacency matrix.For example, consider the following graph: The number of paths from vertex 0 to vertex 3 with length 2 is 2 ({0-&gt;
1 min read
Minimum time required to transport all the boxes from source to the destination under the given constraints
Given two arrays, box[] and truck[], where box[i] represents the weight of the ith box and truck[i] represents the maximum load that the ith truck can carry. Now each truck takes 1 hour to transport a box from source to destination and another one hour to come back. Now, given that all the boxes are kept at the source, the task is to find the minim
10 min read
Sum of shortest distance on source to destination and back having at least a common vertex
Given a directed weighted graph and the source and destination vertex. The task is to find the sum of shortest distance on the path going from source to destination and then from destination to source such that both the paths have at least a common vertex other than the source and the destination. Note: On going from destination to source, all the
15+ min read
Count total ways to reach destination from source in an undirected Graph
Given an undirected graph, a source vertex ‘s’ and a destination vertex ‘d’, the task is to count the total paths from the given ‘s’ to ‘d’. Examples Input: s = 1, d = 4 Output: 2 Explanation: Below are the 2 paths from 1 to 4 1 -&gt; 3 -&gt; 4 1 -&gt; 2 -&gt; 3 -&gt; 4 Input: s = 3, d = 9 Output: 6 Explanation: Below are the 6 paths from 3 to 9 3
12 min read
Print all shortest paths between given source and destination in an undirected graph
Given an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: Input: source = 0, destination = 5 Output: 0 -&gt; 1 -&gt; 3 -&gt; 50 -&gt; 2 -&gt; 3 -&gt; 50 -&gt; 1 -&gt; 4 -&gt; 5 Explanation: All the above paths are of
13 min read
Minimize steps defined by a string required to reach the destination from a given source
Given a string str and four integers X1, Y1, X2 and Y2, where (X1, Y1) denotes the source coordinates and (X2, Y2) denotes the coordinates of the destination. Given a string str, the task is to find the minimum number of steps of the following four types required to reach destination from the source: If str[i] = 'E': Convert (X1, Y1) to (X1 + 1, Y1
11 min read
Check if a destination is reachable from source with two movements allowed | Set 2
Given a pair of coordinates (X1, Y1)(source) and (X2, Y2)(destination), the task is to check if it is possible to reach the destination form the source by the following movements from any cell (X, Y): (X + Y, Y)(X, Y + X) Note: All coordinates are positive and can be as large as 1018. Examples: Input: X1 = 2, Y1 = 10, X2 = 26, Y2 = 12 Output: Yes E
7 min read
Count of all unique paths from given source to destination in a Matrix
Given a 2D matrix of size n*m, a source ‘s’ and a destination ‘d’, print the count of all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down. Examples: Input: arr[][] = { {1, 2, 3}, {4, 5, 6} }, s = {0, 0}, d = {1, 2}Output: 3Explanation: All possible paths from source to destination are: 1 -&gt; 4 -
4 min read
Print all unique paths from given source to destination in a Matrix moving only down or right
Given a 2-D array mat[][], a source ‘s’ and a destination ‘d’, print all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}}, s[] = {0, 0}, d[]={1, 2}Output: 1 4 5 61 2 5 61 2 3 6 Input: mat[][] = {{1, 2}, {3, 4}}, s[] = {0, 1}, d[] = {1, 1}Output: 2 4
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg