import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { a[i][j] = in.nextInt(); } } int[][] dp = new int[n + 1][m + 1]; // 第一行、第一列只能够从前一列、前一行到达 for (int i = 1; i <= n; i++)dp[i][1] = dp[i - 1][1] + a[i][1]; for (int i = 1; i <= m; i++)dp[1][i] = dp[1][i - 1] + a[1][i]; for (int i = 2; i <= n; i++) { for (int j = 2; j <= m; j++) { dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + a[i][j]; } } System.out.println(dp[n][m]); } }
二维dp