https://leetcode-cn.com/problems/minimum-path-sum/
package com.cn.dl.leetcode;
/**
* Created by yanshao on 2020-02-22.
*/
public class MinPathSum {
/**
* 简单的动态规划,算出每一个节点到下一个节点的路径之和
* */
public int minPathSum(int[][] grid) {
if(grid == null || grid.length == 0 ){
return 0;
}
int[][] minPathSum = new int[grid.length][grid[0].length];
minPathSum[0][0] = grid[0][0];
//先算第一行从前一个节点到下一个节点之和
for(int i = 1; i < grid[0].length; i++){
minPathSum[0][i] = grid[0][i] + minPathSum[0][i-1];
}
//再算第一列从前一个节点到下一个节点之和
for(int j = 1; j < grid.length; j++){
minPathSum[j][0] = grid[j][0] + minPathSum[j - 1][0];
}
//接下来从(1,1),算从上一个节点到当前节点之和
for(int i = 1; i < grid.length; i++){
for(int j = 1; j < grid[0].length; j++){
minPathSum[i][j] = Math.min(minPathSum[i-1][j],minPathSum[i][j-1]) + grid[i][j];
}
}
//最后(grid.length - 1,grid[0].length - 1)节点的值,就是从左上角到右下角的最短路径
return minPathSum[grid.length - 1][grid[0].length - 1];
}
public static void main(String[] args) {
int[][] grid = new int[][]{
{1,3,1},
{1,5,1},
{4,2,1}
};
System.out.println(new MinPathSum().minPathSum(grid));
}
}