There are N stations on route of a train. The train goes from station 0 to N-1. The ticket cost for all pair of stations (i, j) is given where j is greater than i. Find the minimum cost to reach the destination.
Consider the following example:
Input:
cost[N][N] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
There are 4 stations and cost[i][j] indicates cost to reach j
from i. The entries where j < i are meaningless.
Output:
The minimum cost is 65
The minimum cost can be obtained by first going to station 1
from 0. Then from station 1 to station 3.
The minimum cost to reach N-1 from 0 can be recursively written as following:
minCost(0, N-1) = MIN { cost[0][n-1],
cost[0][1] + minCost(1, N-1),
minCost(0, 2) + minCost(2, N-1),
........,
minCost(0, N-2) + cost[N-2][n-1] }
The following is the implementation of above recursive formula.
C++
#include<iostream>
#include<climits>
using namespace std;
#define INF INT_MAX
#define N 4
int minCostRec( int cost[][N], int s, int d)
{
if (s == d || s+1 == d)
return cost[s][d];
int min = cost[s][d];
for ( int i = s+1; i<d; i++)
{
int c = minCostRec(cost, s, i) +
minCostRec(cost, i, d);
if (c < min)
min = c;
}
return min;
}
int minCost( int cost[][N])
{
return minCostRec(cost, 0, N-1);
}
int main()
{
int cost[N][N] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
cout << "The Minimum cost to reach station "
<< N << " is " << minCost(cost);
return 0;
}
|
Java
class shortest_path
{
static int INF = Integer.MAX_VALUE,N = 4 ;
static int minCostRec( int cost[][], int s, int d)
{
if (s == d || s+ 1 == d)
return cost[s][d];
int min = cost[s][d];
for ( int i = s+ 1 ; i<d; i++)
{
int c = minCostRec(cost, s, i) +
minCostRec(cost, i, d);
if (c < min)
min = c;
}
return min;
}
static int minCost( int cost[][])
{
return minCostRec(cost, 0 , N- 1 );
}
public static void main(String args[])
{
int cost[][] = { { 0 , 15 , 80 , 90 },
{INF, 0 , 40 , 50 },
{INF, INF, 0 , 70 },
{INF, INF, INF, 0 }
};
System.out.println( "The Minimum cost to reach station " + N+
" is " +minCost(cost));
}
}
|
Python3
global N
N = 4
def minCostRec(cost, s, d):
if s = = d or s + 1 = = d:
return cost[s][d]
min = cost[s][d]
for i in range (s + 1 , d):
c = minCostRec(cost,s, i) + minCostRec(cost, i, d)
if c < min :
min = c
return min
def minCost(cost):
return minCostRec(cost, 0 , N - 1 )
cost = [ [ 0 , 15 , 80 , 90 ],
[ float ( "inf" ), 0 , 40 , 50 ],
[ float ( "inf" ), float ( "inf" ), 0 , 70 ],
[ float ( "inf" ), float ( "inf" ), float ( "inf" ), 0 ]
]
print ( "The Minimum cost to reach station %d is %d" % \
(N, minCost(cost)))
|
C#
using System;
class GFG {
static int INF = int .MaxValue, N = 4;
static int minCostRec( int [,]cost, int s, int d)
{
if (s == d || s + 1 == d)
return cost[s,d];
int min = cost[s,d];
for ( int i = s + 1; i < d; i++)
{
int c = minCostRec(cost, s, i) +
minCostRec(cost, i, d);
if (c < min)
min = c;
}
return min;
}
static int minCost( int [,]cost)
{
return minCostRec(cost, 0, N-1);
}
public static void Main()
{
int [,]cost = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0} };
Console.WriteLine( "The Minimum cost to"
+ " reach station " + N
+ " is " +minCost(cost));
}
}
|
PHP
<?php
$INF = PHP_INT_MAX ;
$N = 4;
function minCostRec( $cost , $s , $d )
{
if ( $s == $d || $s +1 == $d )
return $cost [ $s ][ $d ];
$min = $cost [ $s ][ $d ];
for ( $i = $s +1; $i < $d ; $i ++)
{
$c = minCostRec( $cost , $s , $i ) +
minCostRec( $cost , $i , $d );
if ( $c < $min )
$min = $c ;
}
return $min ;
}
function minCost( $cost )
{
global $N ;
return minCostRec( $cost , 0, $N -1);
}
$cost = array ( array (0, 15, 80, 90),
array (INF, 0, 40, 50),
array (INF, INF, 0, 70),
array (INF, INF, INF, 0)
);
echo "The Minimum cost to reach station " ,
$N , " is " , minCost( $cost );
?>
|
Javascript
<script>
let INF = Number.MAX_VALUE,N = 4;
function minCostRec(cost, s, d)
{
if (s == d || s+1 == d)
return cost[s][d];
let min = cost[s][d];
for (let i = s+1; i<d; i++)
{
let c = minCostRec(cost, s, i) +
minCostRec(cost, i, d);
if (c < min)
min = c;
}
return min;
}
function minCost(cost)
{
return minCostRec(cost, 0, N-1);
}
let cost = [ [0, 15, 80, 90],
[INF, 0, 40, 50],
[INF, INF, 0, 70],
[INF, INF, INF, 0]
];
document.write( "The Minimum cost to reach station " + N+
" is " +minCost(cost));
</script>
|
Output
The Minimum cost to reach station 4 is 65
Time complexity of the above implementation is exponential as it tries every possible path from 0 to N-1. The above solution solves same subproblems multiple times (it can be seen by drawing recursion tree for minCostPathRec(0, 5).
Since this problem has both properties of dynamic programming problems ((see this and this). Like other typical Dynamic Programming(DP) problems, re-computations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in bottom up manner.
One dynamic programming solution is to create a 2D table and fill the table using above given recursive formula. The extra space required in this solution would be O(N2) and time complexity would be O(N3)
We can solve this problem using O(N) extra space and O(N2) time. The idea is based on the fact that given input matrix is a Directed Acyclic Graph (DAG). The shortest path in DAG can be calculated using the approach discussed in below post.
Shortest Path in Directed Acyclic Graph
We need to do less work here compared to above mentioned post as we know topological sorting of the graph. The topological sorting of vertices here is 0, 1, …, N-1. Following is the idea once topological sorting is known.
The idea in below code is to first calculate min cost for station 1, then for station 2, and so on. These costs are stored in an array dist[0…N-1].
- The min cost for station 0 is 0, i.e., dist[0] = 0
- The min cost for station 1 is cost[0][1], i.e., dist[1] = cost[0][1]
- The min cost for station 2 is minimum of following two.
- dist[0] + cost[0][2]
- dist[1] + cost[1][2]
- The min cost for station 3 is minimum of following three.
- dist[0] + cost[0][3]
- dist[1] + cost[1][3]
- dist[2] + cost[2][3]
Similarly, dist[4], dist[5], … dist[N-1] are calculated.
Below is the implementation of above idea.
C++
#include<iostream>
#include<climits>
using namespace std;
#define INF INT_MAX
#define N 4
int minCost( int cost[][N])
{
int dist[N];
for ( int i=0; i<N; i++)
dist[i] = INF;
dist[0] = 0;
for ( int i=0; i<N; i++)
for ( int j=i+1; j<N; j++)
if (dist[j] > dist[i] + cost[i][j])
dist[j] = dist[i] + cost[i][j];
return dist[N-1];
}
int main()
{
int cost[N][N] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
cout << "The Minimum cost to reach station "
<< N << " is " << minCost(cost);
return 0;
}
|
Java
class shortest_path
{
static int INF = Integer.MAX_VALUE,N = 4 ;
static int minCost( int cost[][])
{
int dist[] = new int [N];
for ( int i= 0 ; i<N; i++)
dist[i] = INF;
dist[ 0 ] = 0 ;
for ( int i= 0 ; i<N; i++)
for ( int j=i+ 1 ; j<N; j++)
if (dist[j] > dist[i] + cost[i][j])
dist[j] = dist[i] + cost[i][j];
return dist[N- 1 ];
}
public static void main(String args[])
{
int cost[][] = { { 0 , 15 , 80 , 90 },
{INF, 0 , 40 , 50 },
{INF, INF, 0 , 70 },
{INF, INF, INF, 0 }
};
System.out.println( "The Minimum cost to reach station " + N+
" is " +minCost(cost));
}
}
|
Python3
INF = 2147483647
N = 4
def minCost(cost):
dist = [ 0 for i in range (N)]
for i in range (N):
dist[i] = INF
dist[ 0 ] = 0
for i in range (N):
for j in range (i + 1 ,N):
if (dist[j] > dist[i] + cost[i][j]):
dist[j] = dist[i] + cost[i][j]
return dist[N - 1 ]
cost = [ [ 0 , 15 , 80 , 90 ],
[INF, 0 , 40 , 50 ],
[INF, INF, 0 , 70 ],
[INF, INF, INF, 0 ]]
print ( "The Minimum cost to reach station " ,
N, " is " ,minCost(cost))
|
C#
using System;
class GFG {
static int INF = int .MaxValue, N = 4;
static int minCost( int [,]cost)
{
int []dist = new int [N];
for ( int i = 0; i < N; i++)
dist[i] = INF;
dist[0] = 0;
for ( int i = 0; i < N; i++)
for ( int j = i + 1; j < N; j++)
if (dist[j] > dist[i] + cost[i,j])
dist[j] = dist[i] + cost[i,j];
return dist[N-1];
}
public static void Main()
{
int [,]cost = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0} };
Console.WriteLine( "The Minimum cost to"
+ " reach station " + N
+ " is " +minCost(cost));
}
}
|
PHP
<?php
$INF =PHP_INT_MAX;
$N = 4;
function minCost( $cost )
{
global $INF ;
global $N ;
$dist [ $N ]= array ();
for ( $i =0; $i < $N ; $i ++)
$dist [ $i ] = $INF ;
$dist [0] = 0;
for ( $i =0; $i < $N ; $i ++)
for ( $j = $i +1; $j < $N ; $j ++)
if ( $dist [ $j ] > $dist [ $i ] + $cost [ $i ][ $j ])
$dist [ $j ] = $dist [ $i ] + $cost [ $i ][ $j ];
return $dist [ $N -1];
}
$cost = array ( array (0, 15, 80, 90),
array (INF, 0, 40, 50),
array (INF, INF, 0, 70),
array (INF, INF, INF, 0));
echo "The Minimum cost to reach station " ,
$N , " is " ,minCost( $cost );
?>
|
Javascript
<script>
let INF = Number.MAX_VALUE, N = 4;
function minCost(cost)
{
let dist = new Array(N);
dist.fill(0);
for (let i = 0; i < N; i++)
dist[i] = INF;
dist[0] = 0;
for (let i = 0; i < N; i++)
for (let j = i + 1; j < N; j++)
if (dist[j] > dist[i] + cost[i][j])
dist[j] = dist[i] + cost[i][j];
return dist[N-1];
}
let cost = [ [0, 15, 80, 90],
[INF, 0, 40, 50],
[INF, INF, 0, 70],
[INF, INF, INF, 0] ];
document.write( "The Minimum cost to"
+ " reach station " + N
+ " is " +minCost(cost));
</script>
|
Output
The Minimum cost to reach station 4 is 65
Time Complexity: O(n2) (two nested for loop)
Auxiliary Space: O(n) (as we are storing answer in dist vector)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!