|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.StringTokenizer; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int[] dx = {-1, 1, 0, 0}; |
| 7 | + static int[] dy = {0, 0, -1, 1}; |
| 8 | + |
| 9 | + static int R, C; |
| 10 | + static int[][] map; |
| 11 | + static int answer = Integer.MIN_VALUE; |
| 12 | + |
| 13 | + public static void main(String[] args) throws IOException { |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 16 | + R = Integer.parseInt(st.nextToken()); |
| 17 | + C = Integer.parseInt(st.nextToken()); |
| 18 | + |
| 19 | + map = new int[R][C]; |
| 20 | + |
| 21 | + for (int i = 0; i < R; i++) { |
| 22 | + st = new StringTokenizer(br.readLine()); |
| 23 | + for (int j = 0; j < C; j++) { |
| 24 | + map[i][j] = Integer.parseInt(st.nextToken()); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + for (int i = 0; i < R; i++) { |
| 29 | + for (int j = 0; j < C; j++) { |
| 30 | + dfs(0, map[i][j], i, j, 0); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + System.out.println(answer); |
| 35 | + } |
| 36 | + |
| 37 | + private static void dfs(int length, int sum, int x, int y, int direction) { |
| 38 | + if (length == 3) { |
| 39 | + answer = Math.max(answer, sum); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + if (length == 1) { |
| 44 | + // ㅗ 모양 처리 |
| 45 | + if (direction == 0 || direction == 1) { // 위/아래로 움직인 경우 |
| 46 | + int nx1 = x + dx[2]; |
| 47 | + int ny1 = y + dy[2]; |
| 48 | + int nx2 = x + dx[3]; |
| 49 | + int ny2 = y + dy[3]; |
| 50 | + if (!cannotMove(nx1, ny1) && !cannotMove(nx2, ny2)) { |
| 51 | + answer = Math.max(answer, sum + map[nx1][ny1] + map[nx2][ny2]); |
| 52 | + } |
| 53 | + } else if (direction == 2 || direction == 3) { // 좌/우로 움직인 경우 |
| 54 | + int nx1 = x + dx[0]; |
| 55 | + int ny1 = y + dy[0]; |
| 56 | + int nx2 = x + dx[1]; |
| 57 | + int ny2 = y + dy[1]; |
| 58 | + if (!cannotMove(nx1, ny1) && !cannotMove(nx2, ny2)) { |
| 59 | + answer = Math.max(answer, sum + map[nx1][ny1] + map[nx2][ny2]); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + for (int i = 0; i < 4; i++) { |
| 65 | + if (length != 0) { |
| 66 | + if (i == 0 && direction == 1) continue; |
| 67 | + if (i == 1 && direction == 0) continue; |
| 68 | + if (i == 2 && direction == 3) continue; |
| 69 | + if (i == 3 && direction == 2) continue; |
| 70 | + } |
| 71 | + int nx = x + dx[i]; |
| 72 | + int ny = y + dy[i]; |
| 73 | + if (cannotMove(nx, ny) ) continue; |
| 74 | + |
| 75 | + dfs(length + 1, sum + map[nx][ny], nx, ny, i); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + private static boolean cannotMove(int nx, int ny) { |
| 80 | + return (nx < 0 || ny < 0 || nx >= R || ny >= C); |
| 81 | + } |
| 82 | +} |
| 83 | +``` |
0 commit comments