/**
* @author xienl
* @description 矩阵的最小路径和
* @date 2022/7/6
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[][] arr = {{1,3,2,9},{8,3,3,4},{5,0,6,1},{8,8,4,0}};
System.out.println(solution.minPathSum(arr));
}
public int minPathSum (int[][] matrix) {
// write code here
int n = matrix.length;
int m = matrix[0].length;
int[][] dp = new int[n][m];
dp[0][0] = matrix[0][0];
// 初始化dp
for (int i = 1; i < n; i++){
dp[i][0] = matrix[i][0] + dp[i - 1][0] ;
}
for (int i = 1; i < m; i++){
dp[0][i] = matrix[0][i] + dp[0][ i - 1];
}
for (int i = 1; i < n; i++){
for (int j = 1; j < m; j++){
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + matrix[i][j];
}
}
return dp[n - 1][m - 1];
}
}