https://www.acmicpc.net/problem/14500

 

문제

폴리오미노란 크기가 1×1인 정사각형을 여러 개 이어서 붙인 도형이며, 다음과 같은 조건을 만족해야 한다.

  • 정사각형은 서로 겹치면 안 된다.
  • 도형은 모두 연결되어 있어야 한다.
  • 정사각형의 변끼리 연결되어 있어야 한다. 즉, 꼭짓점과 꼭짓점만 맞닿아 있으면 안 된다.

정사각형 4개를 이어 붙인 폴리오미노는 테트로미노라고 하며, 다음과 같은 5가지가 있다.

아름이는 크기가 N×M인 종이 위에 테트로미노 하나를 놓으려고 한다. 종이는 1×1 크기의 칸으로 나누어져 있으며, 각각의 칸에는 정수가 하나 쓰여 있다.

테트로미노 하나를 적절히 놓아서 테트로미노가 놓인 칸에 쓰여 있는 수들의 합을 최대로 하는 프로그램을 작성하시오.

테트로미노는 반드시 한 정사각형이 정확히 하나의 칸을 포함하도록 놓아야 하며, 회전이나 대칭을 시켜도 된다.

입력

첫째 줄에 종이의 세로 크기 N과 가로 크기 M이 주어진다. (4 ≤ N, M ≤ 500)

둘째 줄부터 N개의 줄에 종이에 쓰여 있는 수가 주어진다. i번째 줄의 j번째 수는 위에서부터 i번째 칸, 왼쪽에서부터 j번째 칸에 쓰여 있는 수이다. 입력으로 주어지는 수는 1,000을 넘지 않는 자연수이다.

출력

첫째 줄에 테트로미노가 놓인 칸에 쓰인 수들의 합의 최댓값을 출력한다.

 

 

구현 문제

특정한 테트리스들의 모양이 한정되어 있으므로 그 특정한 모양들을 어떻게 저장하고, 종이에 붙일 것인지 생각해야 했다. 논리적인 로직 자체는 어렵지 않은데, 이걸 컴퓨터가 알아들을 수 있는 코드로 표현하기에는 어렵게 느껴지는 전형적인 구현 문제라고 생각했다.

 

 

테트리스를 어떻게 저장할까?

먼저 테트리스의 제한된 경우의 수를 모두 파악해보자.

 

나는 먼저 테트리스의 종류가 5가지밖에 안된다는 것에 주목했다. 회전하고 대칭시켜서 나오는 모양도 총 19개였다. 이런식으로 갯수가 작게 제한되어 있는 재료라면, 직접 경우의 수를 전부 만들어 저장해놓고, 부르트포스 하는게 편하다고 생각했다.

 

① 테트리스 ② 90º 회전 ③ 180º 회전 ④ 270º 회전 ⑤ 좌우 반전 ⑥ 90º 회전 ⑦ 180º 회전 ⑧ 270º 회전

모형대신 숫자가 들어간 칸은 같은 행의 해당 숫자에 해당하는 열의 도형과 일치한다는 의미이다.

테트리스는 이렇게 총 19가지로 제한된다.

 

 

그러면 19가지의 경우의 테트리스를 어떻게 저장해 놓을까?

처음에는 좌표로 저장해놓아야 겠다고 생각했다. 다음과 같이 말이다.

    static ArrayList<int[][]> getTETRIS() {
        ArrayList<int[][]> TETRIS = new ArrayList<>();
        
        TETRIS.add(new int[][]{{0, 0}, {0, 1}, {0, 2}, {0, 3}}); // ㅡ
        TETRIS.add(new int[][]{{0, 0}, {1, 0}, {2, 0}, {3, 0}}); // |

        TETRIS.add(new int[][]{{0, 0}, {0, 1}, {1, 0}, {1, 1}}); // ㅁ

        TETRIS.add(new int[][]{{0, 0}, {1, 0}, {2, 0}, {2, 1}}); // L
        TETRIS.add(new int[][]{{0, 0}, {1, 0}, {1, -1}, {1, -2}}); // ──┘
        TETRIS.add(new int[][]{{0, 0}, {0, 1}, {1, 1}, {2, 1}}); // ┐
        TETRIS.add(new int[][]{{0, 0}, {0, 1}, {0, 2}, {1, 0}}); // ┌──
        TETRIS.add(new int[][]{{0, 0}, {1, 0}, {2, 0}, {2, -1}}); // ┘
        TETRIS.add(new int[][]{{0, 0}, {1, 0}, {1, 1}, {1, 2}}); // └──
        TETRIS.add(new int[][]{{0, 0}, {0, 1}, {1, 0}, {2, 0}}); // ┌
        TETRIS.add(new int[][]{{0, 0}, {0, 1}, {0, 2}, {1, 2}}); // ──┐
        
        TETRIS.add(new int[][]{{0, 0}, {1, 0}, {1, 1}, {2, 1}}); // └┐
        TETRIS.add(new int[][]{{0, 0}, {0, 1}, {1, 0}, {1, -1}}); // z 반대로
        TETRIS.add(new int[][]{{0, 0}, {1, 0}, {1, -1}, {2, -1}}); // ┌┘
        TETRIS.add(new int[][]{{0, 0}, {0, 1}, {1, 1}, {1, 2}}); // z

        TETRIS.add(new int[][]{{0, 0}, {0, 1}, {0, 2}, {1, 1}}); // ㅜ
        TETRIS.add(new int[][]{{0, 0}, {1, 0}, {2, 0}, {1, -1}}); // ㅓ
        TETRIS.add(new int[][]{{0, 0}, {1, -1}, {1, 0}, {1, 1}}); // ㅗ
        TETRIS.add(new int[][]{{0, 0}, {1, 0}, {2, 0}, {1, 1}}); // ㅏ

        return TETRIS;
    }

 

그런데 이렇게 구현하다보니... 문제점이 보였다.

 

좌표로 관리할 경우 문제점.

  1. 직관적이지 않다.
    어떤 모양인지 바로바로 알 수가 없다. 실수할 가능성이 매우 높아진다.

  2. 어느 점을 기준으로 할 것인지 명확하지 않다.
    다음을 보면 같은 모양임에도, 좌표 값이 다르게 나타나는 것을 볼 수 있다.
    그렇다. 어느 점을 기준으로 잡느냐에 따라서 좌표값이 달라진다.
    이런식으로 되면 기준을 잡기가 상당히 복잡해진다. 

 

그래서 직관적으로 바꿔봤어요!

모양 자체를 직관적으로 저장해서, 비교할 수 있도록!

    static ArrayList<int[][]> getTETRIS() {
        ArrayList<int[][]> TETRIS = new ArrayList<>();

        int[][] tet = new int[][]{{1, 1, 1, 1}};
        TETRIS.add(tet); // ㅡ
        TETRIS.add(rotateClockwise(tet, 90)); // ㅣ
        
        tet = new int[][]{
                {1, 1},
                {1, 1}
        };
        TETRIS.add(tet); // ㅁ

        tet = new int[][]{
                {1, 0},
                {1, 0},
                {1, 1}
        };
        TETRIS.add(tet); // L
        TETRIS.add(rotateClockwise(tet, 90)); // ┌──
        TETRIS.add(rotateClockwise(tet, 180)); // ┐
        TETRIS.add(rotateClockwise(tet, 270)); // ──┘

        tet = mirrorHorizontally(tet);
        TETRIS.add(tet); // ┘
        TETRIS.add(rotateClockwise(tet, 90)); // └──
        TETRIS.add(rotateClockwise(tet, 180)); // ┌
        TETRIS.add(rotateClockwise(tet, 270)); // ──┐

        tet = new int[][]{
                {1, 0},
                {1, 1},
                {0, 1}
        };
        TETRIS.add(tet); // └┐
        TETRIS.add(rotateClockwise(tet, 90)); // z 반대로

        tet = mirrorHorizontally(tet);
        TETRIS.add(tet); // ┌┘
        TETRIS.add(rotateClockwise(tet, 90)); // z

        tet = new int[][]{
                {1, 1, 1},
                {0, 1, 0}
        };
        TETRIS.add(tet); // ㅜ
        TETRIS.add(rotateClockwise(tet, 90)); // ㅓ
        TETRIS.add(rotateClockwise(tet, 180)); // ㅗ
        TETRIS.add(rotateClockwise(tet, 270)); // ㅏ

        return TETRIS;
    }

    static int[][] rotateClockwise(int[][] intArr, int angle) {
        int n = intArr.length;
        int m = intArr[0].length;
        int[][] rotated = new int[m][n];
        if (angle == 180) rotated = new int[n][m];

        for (int i=0; i<n; i++) {
            for (int j=0; j<m; j++) {
                switch (angle) {
                    case 90:
                        rotated[j][n - 1 - i] = intArr[i][j];
                        break;
                    case 180:
                        rotated[n - 1 - i][m - 1 - j] = intArr[i][j];
                        break;
                    case 270:
                        rotated[m - 1 - j][i] = intArr[i][j];
                        break;
                }
            }
        }

        return rotated;
    }

    static int[][] mirrorHorizontally(int[][] intArr) {
        int n = intArr.length;
        int m = intArr[0].length;

        int[][] mirrored = new int[n][m];

        for (int i=0; i<n; i++) {
            for (int j=0; j<m; j++) {
                mirrored[i][m - 1 - j] = intArr[i][j];
            }
        }

        return mirrored;
    }

 

좌표를 회전하고 좌우반전하는 코드로, 직접 일일히 넣지 않아도 되게끔 구현해보았다.

 

그럼 이제 전체 MAP 을 돌려보면서 각 테트리스를 맞춰가며 Score 를 계산해보자.

for (int[][] tet : TETRIS) {
    for (int i=0; i<n; i++) {
        // 현재 테트리스가 현재 x칸에 들어갈 수 있는지 확인
        if (i + (tet.length - 1) >= n) break;
        for (int j = 0; j < m; j++) {
            // 현재 테트리스가 현재 y칸에 들어갈 수 있는지 확인
            if (j + (tet[0].length - 1) >= m) break;

            // 안들어간다면, 다음칸으로 -> break

            // 들어간다면, 최댓값 계산.
            MAX = Math.max(MAX, getScore(i, j, tet));
        }
    }
}
    static int getScore(int x, int y, int[][] tet) {
        int result = 0; // 최종 score
        for (int i=0; i<tet.length; i++) {
            for (int j=0; j<tet[i].length; j++) {
            	// 만약 현재 칸이 현재 선정된 tetris 모양의 범위가 맞다면(1이라면)
                if (tet[i][j] == 1) result += MAP[x+i][y+j]; // 해당 칸의 score 합산.
            }
        }
        return result;
    }

 

전체 최종 코드

import java.io.*;
import java.util.*;

public class Solution {

    static int[][] MAP = null;
    static ArrayList<int[][]> TETRIS = null;
    static int MAX = Integer.MIN_VALUE;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int[] nm = getIntArr(br.readLine().split(" "));
        int n = nm[0];
        int m = nm[1];

        TETRIS = getTETRIS();
        // 저장된 테트리스 모양 전체 출력해보기
//        for (int[][] tet : TETRIS) {
//            printArray(tet);
//        }
        MAP = new int[n][m];
        for (int i=0; i<n; i++) {
            MAP[i] = getIntArr(br.readLine().split(" "));
        }

        for (int[][] tet : TETRIS) {
            for (int i=0; i<n; i++) {
                // 현재 테트리스가 현재 x칸에 들어갈 수 있는지 확인
                if (i + (tet.length - 1) >= n) break;
                for (int j = 0; j < m; j++) {
                    // 현재 테트리스가 현재 y칸에 들어갈 수 있는지 확인
                    if (j + (tet[0].length - 1) >= m) break;

                    // 안들어간다면, 다음칸으로 -> break

                    // 들어간다면, 최댓값 계산.
                    MAX = Math.max(MAX, getScore(i, j, tet));
                }
            }
        }


        System.out.println(MAX);

    }

    static int getScore(int x, int y, int[][] tet) {
        int result = 0;
        for (int i=0; i<tet.length; i++) {
            for (int j=0; j<tet[i].length; j++) {
                if (tet[i][j] == 1) result += MAP[x+i][y+j];
            }
        }
        return result;
    }

    static ArrayList<int[][]> getTETRIS() {
        ArrayList<int[][]> TETRIS = new ArrayList<>();

        int[][] tet = new int[][]{{1, 1, 1, 1}};
        TETRIS.add(tet); // ㅡ
        TETRIS.add(rotateClockwise(tet, 90)); // ㅣ

        tet = new int[][]{
                {1, 1},
                {1, 1}
        };
        TETRIS.add(tet); // ㅁ

        tet = new int[][]{
                {1, 0},
                {1, 0},
                {1, 1}
        };
        TETRIS.add(tet); // L
        TETRIS.add(rotateClockwise(tet, 90)); // ┌──
        TETRIS.add(rotateClockwise(tet, 180)); // ┐
        TETRIS.add(rotateClockwise(tet, 270)); // ──┘

        tet = mirrorHorizontally(tet);
        TETRIS.add(tet); // ┘
        TETRIS.add(rotateClockwise(tet, 90)); // └──
        TETRIS.add(rotateClockwise(tet, 180)); // ┌
        TETRIS.add(rotateClockwise(tet, 270)); // ──┐

        tet = new int[][]{
                {1, 0},
                {1, 1},
                {0, 1}
        };
        TETRIS.add(tet); // └┐
        TETRIS.add(rotateClockwise(tet, 90)); // z 반대로

        tet = mirrorHorizontally(tet);
        TETRIS.add(tet); // ┌┘
        TETRIS.add(rotateClockwise(tet, 90)); // z

        tet = new int[][]{
                {1, 1, 1},
                {0, 1, 0}
        };
        TETRIS.add(tet); // ㅜ
        TETRIS.add(rotateClockwise(tet, 90)); // ㅓ
        TETRIS.add(rotateClockwise(tet, 180)); // ㅗ
        TETRIS.add(rotateClockwise(tet, 270)); // ㅏ

        return TETRIS;
    }

    static int[][] rotateClockwise(int[][] intArr, int angle) {
        int n = intArr.length;
        int m = intArr[0].length;
        int[][] rotated = new int[m][n];
        if (angle == 180) rotated = new int[n][m];

        for (int i=0; i<n; i++) {
            for (int j=0; j<m; j++) {
                switch (angle) {
                    case 90:
                        rotated[j][n - 1 - i] = intArr[i][j];
                        break;
                    case 180:
                        rotated[n - 1 - i][m - 1 - j] = intArr[i][j];
                        break;
                    case 270:
                        rotated[m - 1 - j][i] = intArr[i][j];
                        break;
                }
            }
        }

        return rotated;
    }

    static int[][] mirrorHorizontally(int[][] intArr) {
        int n = intArr.length;
        int m = intArr[0].length;

        int[][] mirrored = new int[n][m];

        for (int i=0; i<n; i++) {
            for (int j=0; j<m; j++) {
                mirrored[i][m - 1 - j] = intArr[i][j];
            }
        }

        return mirrored;
    }

    static int[] getIntArr(String[] strArr) {
        return Arrays.stream(strArr).mapToInt(Integer::parseInt).toArray();
    }

    public static void printArray(int[][] array) {
        for (int[] row : array) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
        System.out.println();
    }
}

 

끝 ! 헤헤 :) /

테트로미노 파일.xlsx
0.01MB

+ Recent posts