题解 | #矩阵的最小路径和#
矩阵的最小路径和
http://www.nowcoder.com/practice/38ae72379d42471db1c537914b06d48e
dp[i][j]表示到位置i,j的最小路径和
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] nums = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
nums[i][j] = sc.nextInt();
}
}
int[][] dp = new int[n][m];
dp[0][0] = nums[0][0];
for (int i = 1; i < m; i++) {
dp[0][i] = dp[0][i - 1] + nums[0][i];
}
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + nums[i][0];
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = Math.min(dp[i][j - 1] + nums[i][j], dp[i - 1][j] + nums[i][j]);
}
}
System.out.println(dp[n - 1][m - 1]);
}
}