|
| 1 | +``` |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | +
|
| 5 | +public class Main { |
| 6 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + private static final int[] dx = {1, 0}; |
| 9 | + private static final int[] dy = {0, 1}; |
| 10 | + private static int[][] map; |
| 11 | + private static int[][][] dp; |
| 12 | + private static int N; |
| 13 | +
|
| 14 | + public static void main(String[] args) throws IOException { |
| 15 | + init(); |
| 16 | + DP(); |
| 17 | +
|
| 18 | + int answer = 0; |
| 19 | + for (int i = 0; i < 3; i++) { |
| 20 | + answer = Math.max(answer, dp[N-1][N-1][i]); |
| 21 | + } |
| 22 | + bw.write(answer + "\n"); |
| 23 | + bw.flush(); |
| 24 | + bw.close(); |
| 25 | + br.close(); |
| 26 | + } |
| 27 | +
|
| 28 | + private static void init() throws IOException { |
| 29 | + N = Integer.parseInt(br.readLine()); |
| 30 | +
|
| 31 | + map = new int[N][N]; |
| 32 | + dp = new int[N][N][3]; |
| 33 | +
|
| 34 | + for (int i = 0; i < N; i++) { |
| 35 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 36 | + for (int j = 0; j < N; j++) { |
| 37 | + map[i][j] = Integer.parseInt(st.nextToken()); |
| 38 | + Arrays.fill(dp[i][j], -1); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | +
|
| 43 | + private static void DP() { |
| 44 | + if (map[0][0] == 0) dp[0][0][0] = 1; |
| 45 | + dp[0][0][2] = 0; |
| 46 | +
|
| 47 | + for (int i = 0; i < N; i++) { |
| 48 | + for (int j = 0; j < N; j++) { |
| 49 | + for (int k = 0; k < 3; k++) { |
| 50 | + if (dp[i][j][k] == -1) continue; |
| 51 | +
|
| 52 | + for (int l = 0; l < 2; l++) { |
| 53 | + int nx = i + dx[l]; |
| 54 | + int ny = j + dy[l]; |
| 55 | +
|
| 56 | + if (OOB(nx, ny)) continue; |
| 57 | +
|
| 58 | + dp[nx][ny][k] = Math.max(dp[nx][ny][k], dp[i][j][k]); |
| 59 | + |
| 60 | + int next = (k+1)%3; |
| 61 | + if (map[nx][ny] == next) { |
| 62 | + dp[nx][ny][next] = Math.max(dp[nx][ny][next], dp[i][j][k]+1); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | +
|
| 70 | + private static boolean OOB(int nx, int ny) { |
| 71 | + return nx < 0 || nx > N-1 || ny < 0 || ny > N-1; |
| 72 | + } |
| 73 | +
|
| 74 | + private static boolean canDrink(int current, int next) { |
| 75 | + if (current == 0 && next == 1) return true; |
| 76 | +
|
| 77 | + if (current == 1 && next == 2) return true; |
| 78 | +
|
| 79 | + if (current == 2 && next == 0) return true; |
| 80 | +
|
| 81 | + return false; |
| 82 | + } |
| 83 | +} |
| 84 | +``` |
0 commit comments