// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
int m = in.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = in.nextInt();
}
}
System.out.println(minPathSum(matrix));
}
}
public static int minPathSum(int[][] matrix) {
if (matrix == null || matrix.length < 1 || matrix[0] == null || matrix[0].length < 1) {
return 0;
}
int n = matrix.length;
int m = matrix[0].length;
int[][] dp = new int[n][m];
// dp[0][j]
dp[0][0] = matrix[0][0];
for (int j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + matrix[0][j];
}
// dp[i][0]
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + matrix[i][0];
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = Math.min(dp[i - 1][j] + matrix[i][j], dp[i][j - 1] + matrix[i][j]);
}
}
return dp[n - 1][m - 1];
}
}