forked from iRupam/NewtonSchoolInfinityJune21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumCostPath.java
More file actions
74 lines (63 loc) · 1.92 KB
/
MinimumCostPath.java
File metadata and controls
74 lines (63 loc) · 1.92 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package InfinityJune21.DynamicProgramming;
public class MinimumCostPath {
static int min(int num1, int num2, int num3) {
int smallest;
if(num1 < num2) {
if(num1 < num3) {
smallest = num1;
}
else {
smallest = num3;
}
}
else {
if(num2 < num3) {
smallest = num2;
}
else {
smallest = num3;
}
}
/*
smallest = (num1 < num2) ?
((num1 < num3) ? num1 : num3) :
((num2 < num3) ? num2 : num3);
smallest = Math.min(Math.min(num1, num2), num3);
*/
return smallest;
}
static int minimumCost(int cost[][], int m, int n) {
int totalCost[][] = new int[m + 1][n + 1];
totalCost[0][0] = cost[0][0];
//Initialize first row
for(int i = 1; i <= n; i++) {
totalCost[0][i] = totalCost[0][i - 1] + cost[0][i];
}
//Initialize first column
for(int i = 1; i <= m; i++) {
totalCost[i][0] = totalCost[i - 1][0] + cost[i][0];
}
for(int i = 1; i <= m; i++) {
for(int j = 1; j <= n; j++) {
totalCost[i][j] = cost[i][j] +
min(
totalCost[i - 1][j - 1],
totalCost[i - 1][j],
totalCost[i][j - 1]
);
}
}
return totalCost[m][n];
}
public static void main(String[] args) {
int cost[][] = {
{1, 2, 3},
{4, 8, 2},
{1, 5, 3},
{2, 4, 6}
};
int m = 3, n = 2;
int result = minimumCost(cost, m, n);
System.out.println(result);
}
}