Skip to content

Instantly share code, notes, and snippets.

@hnaoto
Created March 6, 2019 06:58
Show Gist options
  • Save hnaoto/9f1cd448612b788acf409f175c094d34 to your computer and use it in GitHub Desktop.
Save hnaoto/9f1cd448612b788acf409f175c094d34 to your computer and use it in GitHub Desktop.
class Solution {
public int minPathSum(int[][] grid) {
int row = grid.length;
int col = grid[0].length;
//dp[i][j] stores the value of minimum path sum at the [i][j]
int[][] dp = new int[row][col];
//initilize the value in dp[][]
dp[0][0] = grid[0][0];
for (int i = 1; i < row; i++) {
dp[i][0] = grid[i][0] + dp[i - 1][0];
}
for (int j = 1; j < col; j++) {
dp[0][j] = grid[0][j] + dp[0][j - 1];
}
//fill in dp[][]
//bc there are only two ways to reach a cell at [i][j] and we are trying to find the minimum path sum,
//we need to choose the smaller path between dp[i - 1][j] and dp[i][j - 1].
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
return dp[row - 1][col - 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment