The idea is to update the matrix, if element has top and/or left neighbor, update the value to be min(left, top) + cur until reach the bottom right.
Return it.
Stay calm and make a wise decision.
public class Solution {
public int minPathSum(int[][] grid) {
if(grid == null){
return Integer.MAX_VALUE;
}
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
int temp = Integer.MAX_VALUE;
if(i - 1 >= 0){
temp = Math.min(temp, grid[i - 1][j]);
}
if(j - 1 >= 0){
temp = Math.min(temp, grid[i][j - 1]);
}
if(i - 1 < 0 && j - 1 < 0){
temp = 0;
}
grid[i][j] = temp + grid[i][j];
}
}
return grid[grid.length - 1][grid[0].length - 1];
}
}
没有评论:
发表评论