forked from codeIIEST/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminCostPath.cpp
55 lines (51 loc) · 1.36 KB
/
minCostPath.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
std::ios::sync_with_stdio(false);
/*
We can easily observe that the optimum solution of the minimum
cost at any row i is only dependent on the cost at row i-1 and
the current row elements. Thus if we only store these two arrays
of length c, We have reduced space from n*m to 2*m.
*/
int i, j, r, c;
printf("Enter no of rows and no of cols\n");
cin>>r>>c; //take input of the rows and columns from user.
int cost[c], dp[c];
int x;
/*
Since for the first row the minimum cost is the only cost possible
required to get there, we directly calculate it.
*/
printf("Enter a R X C array\n");
for(i=0; i<c; i++){
cin>>cost[i];
if(i>0) cost[i] = cost[i] + cost[i-1];
}
/*
For the subsequent rows, the optimised cost for each cell in the
previous row has been stored in the array cost[] and the optimised
cost for the present row is stored in the array dp[].
*/
for(i=1; i<r; i++){
for(j=0; j<c; j++){
cin>>x;
if(j==0)
dp[j] = cost[j] + x;
else{
dp[j] = x + min(dp[j-1], min(cost[j-1], cost[j]));
}
}
/*
After dp[] has been found entirely, we copy its elements to
cost[] and continue the iteration.
*/
for(j=0; (j<c && i!=c-1); j++){
cost[j] = dp[j];
}
}
printf("The min cost path from 1,1 to r,c is\n");
cout<<dp[c-1]<<"\n";
return 0;
}