-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDP5MinimumCostpath.java
More file actions
42 lines (32 loc) · 1.03 KB
/
Copy pathDP5MinimumCostpath.java
File metadata and controls
42 lines (32 loc) · 1.03 KB
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
import java.util.*;
public class DP5MinimumCostpath {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][]arr = new int[n][m];
for(int i=0 ; i<arr.length;i++){
for(int j= 0 ; j<arr[0].length;j++){
arr[i][j]= sc.nextInt();
}
}
int[][] dp = new int[n][m];
for(int i = dp.length -1 ; i>=0 ; i--){
for(int j=dp[0].length -1 ; j>= 0 ; j--){
if(i==dp.length-1 && j==dp[0].length-1){
dp[i][j]=arr[i][j];
}
else if(i==dp.length -1) {
dp[i][j]= dp[i][j+1] + arr[i][j];
}
else if(j==dp[0].length -1){
dp[i][j]= dp[i+1][j] + arr[i][j];
}
else {
dp[i][j]= Math.min(dp[i+1][j], dp[i][j+1]) +arr[i][j];
}
}
}
System.out.println(dp[0][0]);
}
}