|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static final int INF = 1_000_000_000; |
| 8 | + |
| 9 | + public static void main(String[] args) throws Exception { |
| 10 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 12 | + |
| 13 | + int N = Integer.parseInt(st.nextToken()); |
| 14 | + int M = Integer.parseInt(st.nextToken()); |
| 15 | + |
| 16 | + int[][] cost = new int[N][M]; |
| 17 | + for (int i = 0; i < N; i++) { |
| 18 | + st = new StringTokenizer(br.readLine()); |
| 19 | + for (int j = 0; j < M; j++) { |
| 20 | + cost[i][j] = Integer.parseInt(st.nextToken()); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + int[][][] dp = new int[N][M][3]; |
| 25 | + |
| 26 | + for (int j = 0; j < M; j++) { |
| 27 | + for (int d = 0; d < 3; d++) { |
| 28 | + dp[0][j][d] = cost[0][j]; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + for (int i = 1; i < N; i++) { |
| 33 | + for (int j = 0; j < M; j++) { |
| 34 | + Arrays.fill(dp[i][j], INF); |
| 35 | + |
| 36 | + if (j + 1 < M) { |
| 37 | + dp[i][j][0] = Math.min(dp[i - 1][j + 1][1], dp[i - 1][j + 1][2]) + cost[i][j]; |
| 38 | + } |
| 39 | + |
| 40 | + dp[i][j][1] = Math.min(dp[i - 1][j][0], dp[i - 1][j][2]) + cost[i][j]; |
| 41 | + |
| 42 | + if (j - 1 >= 0) { |
| 43 | + dp[i][j][2] = Math.min(dp[i - 1][j - 1][0], dp[i - 1][j - 1][1]) + cost[i][j]; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + int answer = INF; |
| 49 | + for (int j = 0; j < M; j++) { |
| 50 | + for (int d = 0; d < 3; d++) { |
| 51 | + answer = Math.min(answer, dp[N - 1][j][d]); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + System.out.println(answer); |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
0 commit comments