-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinPathSumDP.java
33 lines (25 loc) · 992 Bytes
/
MinPathSumDP.java
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
//https://leetcode.com/problems/minimum-path-sum
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
// Create a dp array to store the minimum path sum to each cell
int[][] dp = new int[m][n];
// Initialize the top-left cell
dp[0][0] = grid[0][0];
// Fill the first row (can only come from the left)
for (int j = 1; j < n; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// Fill the first column (can only come from above)
for (int i = 1; i < m; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// Fill the rest of the dp array
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]);
}
}
// The bottom-right cell contains the minimum path sum
return dp[m - 1][n - 1];
}