Skip to content

Commit b574029

Browse files
author
Dhananjay Nagargoje
committed
DP GRID Minimum cost
1 parent 2ead70d commit b574029

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package problems.onRecursionAndDp.dp;
2+
3+
public class MinimumCostInGrid {
4+
5+
public int minPathSum(int[][] grid) {
6+
int[][] dp = new int[grid.length][grid.length];
7+
dp[0][0] = grid[0][0];
8+
9+
//fill the first row as there is only one way to visit row from right side
10+
//so cost will be cost till previous cell + current grid cost
11+
for (int i=1;i<grid.length;i++) dp[0][i] = dp[0][i-1] + grid[0][i];
12+
13+
//same for first column there is only one way to visit by from top.
14+
for (int i=1;i<grid.length;i++) dp[i][0] = dp[i-1][0] + grid[i][0];
15+
16+
//for remaining each cell there are two possibilities from top and from right
17+
//so to minimize cost take minimum at each step > optimal substructure
18+
//final minimum depends on minimum at each step.
19+
for (int i=1;i<grid.length;i++){
20+
for (int j=1;j<grid.length;j++) {
21+
dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
22+
}
23+
}
24+
25+
return dp[grid.length-1][grid.length-1];
26+
}
27+
28+
public static void main(String[] args) {
29+
int[][] grid = {{1,2,3},{4,5,6}};
30+
System.out.println(grid.length);
31+
System.out.println(grid[0].length);
32+
}
33+
}
34+
/**
35+
64. Minimum Path Sum
36+
Medium
37+
38+
1878
39+
40+
46
41+
42+
Add to List
43+
44+
Share
45+
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
46+
47+
Note: You can only move either down or right at any point in time.
48+
49+
Example:
50+
51+
Input:
52+
[
53+
[1,3,1],
54+
[1,5,1],
55+
[4,2,1]
56+
]
57+
Output: 7
58+
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
59+
*/

0 commit comments

Comments
 (0)