Code : Min Cost Path
1. ((i + 1), j) which is, "down"
2. (i, (j + 1)) which is, "to the right"
3. ((i+1), (j+1)) which is, "to the diagonal"
The first line of the test case contains two integer values, 'M' and 'N', separated by a single space. They represent the 'rows' and 'columns' respectively, for the two-dimensional array/list.
The second line onwards, the next 'M' lines or rows represent the ith row values.
Each of the ith row constitutes 'N' column values separated by a single space.
Print the minimum cost to reach the destination.
1 <= M <= 10 ^ 2
1 <= N <= 10 ^ 2
Time Limit: 1 sec
3 4
3 4 1 2
2 1 8 9
4 7 8 1
13
3 4
10 6 9 0
-23 8 9 90
-200 0 89 200
76
5 6
9 6 0 12 90 1
2 7 8 5 78 6
1 6 0 5 10 -4
9 6 2 -10 7 4
10 -2 0 5 5 7
18
int helper(int **input ,int i,int j,int m,int n,int **output){ if(i==m-1 && j==n-1) return input[i][j];
if(i>=m || j>=n) return INT_MAX;
if(output[i][j]!=-1)return output[i][j]; int x=helper(input,i,j+1,m,n,output); int y=helper(input,i+1,j+1,m,n,output); int z=helper(input,i+1,j,m,n,output); int ans=min(x,min(y,z))+input[i][j]; output[i][j]=ans; return ans;
}
int minCostPath(int **input, int m, int n){ //Write your code here int **output = new int*[m]; for(int i = 0; i < m; i++) { output[i] = new int[n]; for(int j = 0; j < n; j++) { output[i][j] = -1; } } return helper(input,0,0,m,n,output);
}
Comments
Post a Comment