|
| 1 | +package day1014; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.io.*; |
| 5 | + |
| 6 | +public class JY_테트리스_블럭_안의_합_최대화_하기 { |
| 7 | + |
| 8 | + static int N, M; |
| 9 | + static int[][] g; |
| 10 | + static boolean[][] visited; |
| 11 | + static int ans; |
| 12 | + // 현재 그래프 값 중 가장 큰 것 |
| 13 | + static int maxValue; |
| 14 | + static int[] dx = {0, 0, -1, 1}; |
| 15 | + static int[] dy = {-1, 1, 0, 0}; |
| 16 | + |
| 17 | + |
| 18 | + public static void main(String[] args) throws IOException { |
| 19 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 20 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 21 | + |
| 22 | + N = Integer.parseInt(st.nextToken()); |
| 23 | + M = Integer.parseInt(st.nextToken()); |
| 24 | + |
| 25 | + g = new int[N][M]; |
| 26 | + maxValue = Integer.MIN_VALUE; |
| 27 | + for(int i=0; i<N; i++) { |
| 28 | + st = new StringTokenizer(br.readLine()); |
| 29 | + for(int j=0; j<M; j++) { |
| 30 | + g[i][j] = Integer.parseInt(st.nextToken()); |
| 31 | + maxValue = Math.max(maxValue, g[i][j]); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + visited = new boolean[N][M]; |
| 36 | + ans = Integer.MIN_VALUE; |
| 37 | + for(int i=0; i<N; i++) { |
| 38 | + for(int j=0; j<M; j++) { |
| 39 | + visited[i][j] = true; |
| 40 | + dfs(i, j, 1, g[i][j]); |
| 41 | + visited[i][j] = false; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + System.out.println(ans); |
| 46 | + |
| 47 | + } |
| 48 | + public static boolean inRange(int x, int y) { |
| 49 | + return x>=0 && x<N && y>=0 && y<M; |
| 50 | + } |
| 51 | + public static void dfs(int x, int y, int depth, int total) { |
| 52 | + // 4개의 블록 모두 탐색 |
| 53 | + if(depth == 4) { |
| 54 | + ans = Math.max(ans, total); |
| 55 | + return; |
| 56 | + } |
| 57 | + // 가지치기 |
| 58 | + // 현재까지 탐색한 결과에 앞으로 최댓값만 추가한다고 해도 ans값보다 작으면 탐색X |
| 59 | + if(ans >= total+maxValue*(4-depth)) return; |
| 60 | + |
| 61 | + for(int i=0; i<4; i++) { |
| 62 | + int nx = x + dx[i]; |
| 63 | + int ny = y + dy[i]; |
| 64 | + if(!inRange(nx, ny)) continue; |
| 65 | + if(visited[nx][ny]) continue; |
| 66 | + // 2번째 블럭인 경우, ᅡ ᅥ ᅩ ᅮ 처럼 2번째 블록에서 연결된 2개의 블록을 찾아야한다. |
| 67 | + if(depth == 2) { |
| 68 | + visited[nx][ny] = true; |
| 69 | + dfs(x, y, depth+1, total+g[nx][ny]); |
| 70 | + visited[nx][ny] = false; |
| 71 | + } |
| 72 | + |
| 73 | + // 2번쨰 블록 이외에는 일반탐색 |
| 74 | + visited[nx][ny] = true; |
| 75 | + dfs(nx, ny, depth+1, total+g[nx][ny]); |
| 76 | + visited[nx][ny] = false; |
| 77 | + |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments