Open In App

Time saved travelling in shortest route and shortest path through given city

Last Updated : 22 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a matrix mat[][] of size N * N, where mat[i][j] represents the time taken to reach from ith city to jth city. Also, given M queries in the form of three arrays S[], I[], and D[] representing source, intermediate, and destination respectively. The task is to find the time taken to go from S[i] to D[i] using I[i] city and the time that can be saved if we go using the shortest path from S[i] to D[i].

Examples:

Input: N = 4, M = 2
mat[][]: { {0, 2, 1, 4}, {1, 0, 4, 1}, {3, 1, 0, 3}, {1, 1, 1, 0} }
S[] = {1, 0}, I[] = {2, 2}, D[] = {3, 1} 
Output: 
4 3
2 0
Explanation:
Query 1:  

  • Source, Intermediate and Destination city are S1 = 1, I1 = 2, D1 = 3 respectively.
  • Travelling source to destination (1 ->3) city using intermediate (2) city:
    • We can use cities as: 1 -> 0 -> 2 -> 1 -> 3, total time taken will be M[1][0] + M[0][2] + M[2][1] + M[1][3] = 1+1+1+1 = 4. It can be verified that it is the minimum possible time to use an intermediate city for travelling sources to the destination city. 
  • Travelling source to destination (1 ->3) city directly: 
    • The most optimal path will be: 1 -> 3, Total time taken will be = M[1][3] = 1.
  • So that the time taken from source to destination city using intermediate city is: 4, while the time that can be saved if travelled directly from source to destination is: 4-1=3 Therefore, the output is 4 3

The time that will take with the intermediate and time that can be saved if not travelled from the intermediate city are 4, and 3 respectively.  Therefore, the output is 4 3.
Query 2:

  • Source, Intermediate and Destination city are S2=0, I2=2, D2=1 respectively
  • Travelling source to destination (0 ->1) city using intermediate (2) city:
    • We can use cities as:  0 -> 2 -> 1, Total time taken will be M[0][2] + M[2][1] = 1+1 = 2. It can be verified that it is the minimum possible time using intermediate city for travelling source to destination city. 
  • Travelling source to destination (0 -> 1) city directly:
    • The most optimal path will be: 0 -> 1, Total time taken will be = M[0][1] = 2.
  • So that the time taken from source to destination city using intermediate city is: 2, while the time that can be saved if travelled directly from source to destination is: 2-2 = 0. Therefore, the output is 2 0.

Input:  N = 4, M = 3
mat[][] = {0, 2, 4}, {1, 0, 7}, {3, 2, 0} }
S[] = {0, 2, 1}, I[] = {1, 1, 2}, D[] = {3, 2, 0}
Output:
7 3 
3 0
7 7

Approach: Implement the idea below to solve the problem:

The problem is based on shortest path technique and can be solved by using all pair shortest path approach for all the cities.  

Steps were taken to solve the problem:

  1. Run three nested loops for i = 0, j = 0, k = 0 to i < n, j < n, k < n respectively, and follow below mentioned steps under the scope of loop:
    • Calculate time[i][j] as the minimum of mat[i][j] and (mat[i][k] + mat[k][j] )
  2. Run a loop from i=0 to M and do the following:
    • Create three variables S, IN and D and initialize them equal to S[i], I[i] and D[i] respectively.
    • Output the value of mat[S][IN] + mat[IN][D] and  mat[S][IN] + mat[IN][D] – mat[S][D].

Below is the code to implement the approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
int main() {
 
    // Number of cities
    int n = 4;
 
    // Matrix holding time such that time[i][j]
    // denotes time taken to reach from i
    // to j  city
    int time[4][4] = { { 0, 2, 1, 4 },
                     { 1, 0, 4, 1 },
                     { 3, 1, 0, 3 },
                     { 1, 1, 1, 0 } };
 
    // Number of queries
    int m = 2;
 
    // Arrays containing Number of city as
    // source, destination and intermediate
    int source[] = { 1, 0 };
    int intermediate[] = { 2, 2 };
    int destination[] = { 3, 1 };
 
    // Nested loop for all pair shortest paths
    // from i city to j city having shortest
    // intermediate city k
    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                time[i][j] = min(time[i][j], time[i][k] + time[k][j]);
            }
        }
    }
 
    // Loop for number of queries
    for (int i = 0; i < m; i++) {
 
        // Variables containing source,
        // intermediate an   destination
        // cities for per query
        int s = source[i];
        int in = intermediate[i];
        int d = destination[i];
 
        // Time taken if source to destination
        // reached with intermediate city
        int withIntermediate = time[s][in] + time[in][d];
 
        // Time taken if source to destination
        // reached without intermediate city
        int withoutIntermediate = withIntermediate - time[s][d];
 
        // Printing the output
        cout << withIntermediate << " " << withoutIntermediate << endl;
    }
}
 
// This code is contributed by Rahul Sharma


Java




// Java code to implement the approach
 
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
    // Driver Code
    public static void main(String[] args)
        throws java.lang.Exception
    {
 
        // Number of cities
        int n = 4;
 
        // Matrix holding time such that time[i][j]
        // denotes time taken to reach from i
        // to j  city
        int[][] time = { { 0, 2, 1, 4 },
                         { 1, 0, 4, 1 },
                         { 3, 1, 0, 3 },
                         { 1, 1, 1, 0 } };
 
        // Number of queries
        int m = 2;
 
        // Arrays containing Number of city as
        // source, destination and intermediate
        int[] source = { 1, 0 };
        int[] intermediate = { 2, 2 };
        int[] destination = { 3, 1 };
 
        // Nested loop for all pair shortest paths
        // from i city to j city having shortest
        // intermediate city k
        for (int k = 0; k < n; k++) {
 
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    time[i][j] = Integer.min(
                        time[i][j],
                        time[i][k] + time[k][j]);
                }
            }
        }
 
        // Loop for number of queries
        for (int i = 0; i < m; i++) {
 
            // Variables containing source,
            // intermediate and destination
            // cities for per query
            int s = source[i];
            int in = intermediate[i];
            int d = destination[i];
 
            // Time taken if source to destination
            // reached with intermediate city
            int withIntermediate
                = time[s][in] + time[in][d];
 
            // Time taken if source to destination
            // reached without intermediate city
            int withoutIntermediate
                = withIntermediate - time[s][d];
 
            // Printing the output
            System.out.println(withIntermediate + " "
                               + withoutIntermediate);
        }
    }
}


Python3




import sys
import math
 
# Number of cities
n = 4
 
# Matrix holding time such that time[i][j]
# denotes time taken to reach from i to j city
time = [[0, 2, 1, 4],
        [1, 0, 4, 1],
        [3, 1, 0, 3],
        [1, 1, 1, 0]]
 
# Number of queries
m = 2
 
# Arrays containing Number of city as
# source, destination, and intermediate
source = [1, 0]
intermediate = [2, 2]
destination = [3, 1]
 
# Nested loop for all pair shortest paths
# from i city to j city having shortest
# intermediate city k
for k in range(n):
    for i in range(n):
        for j in range(n):
            time[i][j] = min(time[i][j],
                             time[i][k] + time[k][j])
 
# Loop for number of queries
for i in range(m):
 
    # Variables containing source,
    # intermediate and destination
    # cities for per query
    s = source[i]
    in_ = intermediate[i]
    d = destination[i]
 
    # Time taken if source to destination
    # reached with intermediate city
    with_intermediate = time[s][in_] + time[in_][d]
 
    # Time taken if source to destination
    # reached without intermediate city
    without_intermediate = with_intermediate - time[s][d]
 
    # Printing the output
    print(with_intermediate, without_intermediate)


C#




using System;
 
class GFG
{
    // Driver Code
    static void Main(string[] args)
    {
        // Number of cities
        int n = 4;
 
        // Matrix holding time such that time[i][j]
        // denotes time taken to reach from i
        // to j city
        int[,] time = {{0, 2, 1, 4},
                       {1, 0, 4, 1},
                       {3, 1, 0, 3},
                       {1, 1, 1, 0}};
 
        // Number of queries
        int m = 2;
 
        // Arrays containing Number of city as
        // source, destination and intermediate
        int[] source = {1, 0};
        int[] intermediate = {2, 2};
        int[] destination = {3, 1};
 
        // Nested loop for all pair shortest paths
        // from i city to j city having shortest
        // intermediate city k
        for (int k = 0; k < n; k++)
        {
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    time[i, j] = Math.Min(
                        time[i, j],
                        time[i, k] + time[k, j]);
                }
            }
        }
 
        // Loop for number of queries
        for (int i = 0; i < m; i++)
        {
            // Variables containing source,
            // intermediate and destination
            // cities for per query
            int s = source[i];
            int in = intermediate[i];
            int d = destination[i];
 
            // Time taken if source to destination
            // reached with intermediate city
            int withIntermediate
                = time[s, in] + time[in, d];
 
            // Time taken if source to destination
            // reached without intermediate city
            int withoutIntermediate
                = withIntermediate - time[s, d];
 
            // Printing the output
            Console.WriteLine(withIntermediate + " " +
                              withoutIntermediate);
        }
    }
}


Javascript




function GFG() {
 
    // Number of cities
    var n = 4;
 
    // Matrix holding time such that time[i][j]
    // denotes time taken to reach from i
    // to j  city
    var time = [ [0, 2, 1, 4],
                 [1, 0, 4, 1],
                 [3, 1, 0, 3],
                 [1, 1, 1, 0] ];
 
    // Number of queries
    var m = 2;
 
    // Arrays containing Number of city as
    // source, destination and intermediate
    var source = [1, 0];
    var intermediate = [2, 2];
    var destination = [3, 1];
 
    // Nested loop for all pair shortest paths
    // from i city to j city having shortest
    // intermediate city k
    for (var k = 0; k < n; k++) {
 
        for (var i = 0; i < n; i++) {
            for (var j = 0; j < n; j++) {
                time[i][j] = Math.min(time[i][j], time[i][k] + time[k][j]);
            }
        }
    }
 
    // Loop for number of queries
    for (var i = 0; i < m; i++) {
 
        // Variables containing source,
        // intermediate and destination
        // cities for per query
        var s = source[i];
        var in = intermediate[i];
        var d = destination[i];
 
        // Time taken if source to destination
        // reached with intermediate city
        var withIntermediate = time[s][in] + time[in][d];
 
        // Time taken if source to destination
        // reached without intermediate city
        var withoutIntermediate = withIntermediate - time[s][d];
 
        // Printing the output
        console.log(withIntermediate + " " + withoutIntermediate);
    }
}
 
// Call the GFG function
GFG();


Output

4 3
2 0

Time Complexity: O(N3)
Auxiliary Space:  O(N^2), where n is the number of cities. This is because the program uses a 2D array of size n x n to store the time taken to travel between each pair of cities.

Related Articles:



Similar Reads

Number of ways to reach at starting node after travelling through exactly K edges in a complete graph
Given a complete graph having N nodes and N*(N-1)/2 edges and a positive integer K, the task is to find the number of ways if you are starting at node 1 and end at the same node if exactly K edges have to be traversed. Input: N = 4, K = 3Output: 6Explanation: The possible ways are- 1?2?3?1 1?2?4?1 1?3?2?1 1?3?4?1 1?4?2?1 1?4?3?1 Input: N = 5, K = 3
7 min read
Find shortest safe route in a path with landmines
Given a path in the form of a rectangular matrix having few landmines arbitrarily placed (marked as 0), calculate length of the shortest safe route possible from any cell in the first column to any cell in the last column of the matrix. We have to avoid landmines and their four adjacent cells (left, right, above and below) as they are also unsafe.
38 min read
Maximum area that can be saved in the given Matrix
Consider a matrix of N rows and M columns. Initially, there is a cell at co-ordinate (X, Y), which is blue. Then the task is to place the Yellow color in an optimal cell such that the area with yellow color after ending below simulation is the maximum possible. The simulation takes place as follows (after putting a yellow color in a cell): The cell
7 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
19 min read
Difference between the shortest and second shortest path in an Unweighted Bidirectional Graph
Given an unweighted bidirectional graph containing N nodes and M edges represented by an array arr[][2]. The task is to find the difference in length of the shortest and second shortest paths from node 1 to N. If the second shortest path does not exist, print 0. Note: The graph is connected, does not contain multiple edges and self loops. (2&lt;=N
21 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
Finding Minimum travel time to Nearest city from Current location
Given an integer N representing the number of cities near you along with two arrays pos[] representing the position of the city and time[] representing the time required to move 1 unit of distance for a particular city, the task is to find the minimum time required to visit any city where you are currently at cur position. Examples: Input: N = 3, c
6 min read
Bitmasking and Dynamic Programming | Travelling Salesman Problem
In this post, we will be using our knowledge of dynamic programming and Bitmasking technique to solve one of the famous NP-hard problem "Traveling Salesman Problem".Before solving the problem, we assume that the reader has the knowledge of DP and formation of DP transition relationBitmasking in DPTraveling Salesman problem To understand this concep
24 min read
Approximate solution for Travelling Salesman Problem using MST
We introduced Travelling Salesman Problem and discussed Naive and Dynamic Programming Solutions for the problem in the previous post,. Both of the solutions are infeasible. In fact, there is no polynomial time solution available for this problem as the problem is a known NP-Hard problem. There are approximate algorithms to solve the problem though.
3 min read
Travelling Salesman Problem implementation using BackTracking
Travelling Salesman Problem (TSP): Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns back to the starting point.Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exist a tour that v
9 min read
Practice Tags :