Skip to content

Commit f743d5b

Browse files
committed
added min cost path example (dp ref: geekforgeek)
1 parent 752aaec commit f743d5b

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

Dynamic_Programming.java

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,39 @@ public static void main(String[] args) throws Exception {
3232
void solve() throws Exception {
3333
//longest_increasing_subsequence();
3434
//longest_common_subsequence();
35-
edit_distance();
35+
//edit_distance();
36+
min_cost_path();
37+
}
38+
39+
void min_cost_path(){
40+
// Read more :
41+
// http://www.geeksforgeeks.org/dynamic-programming-set-6-min-cost-path/
42+
long cost[][] = { {1, 2, 3},
43+
{4, 8, 2},
44+
{1, 5, 3} };
45+
pout.println(min_cost_dp(cost, 2, 2));
46+
47+
}
48+
49+
long min_cost_dp(long cost[][],int m,int n){
50+
long dp[][] = new long [cost.length][cost[0].length];
51+
dp[0][0] = cost[0][0];
52+
53+
for(int i=1;i<=m;i++){
54+
dp[i][0] = dp[i-1][0] + cost[i][0];
55+
}
56+
57+
for(int j=1;j<=n;j++){
58+
dp[0][j] = dp[0][j-1] + cost[0][j];
59+
}
60+
61+
for(int i=1;i<=m;i++){
62+
for(int j=1;j<=n;j++){
63+
dp[i][j] = cost[i][j] + Math.min(Math.min(dp[i-1][j-1], dp[i][j-1]), dp[i-1][j]);
64+
}
65+
}
66+
67+
return dp[m][n];
3668
}
3769

3870
void edit_distance(){

0 commit comments

Comments
 (0)