[백준] 14500번 C/C++ 풀이 _ 테트로미노



시간 제한메모리 제한제출정답맞은 사람정답 비율
2 초512 MB79702571171430.911%

문제

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

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

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

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

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

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

입력

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

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

출력

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

예제 입력 1 

5 5
1 2 3 4 5
5 4 3 2 1
2 3 4 5 6
6 5 4 3 2
1 2 1 2 1

예제 출력 1 

19

예제 입력 2 

4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

예제 출력 2 

20

예제 입력 3 

4 10
1 2 1 2 1 2 1 2 1 2
2 1 2 1 2 1 2 1 2 1
1 2 1 2 1 2 1 2 1 2
2 1 2 1 2 1 2 1 2 1

예제 출력 3 

7

출처

알고리즘 분류








































- 풀이

미리 모양 벡터 5개를 선언해 놓습니다. 
모양 벡터는 하나의 모양을 기준으로 기준 포인트(왼쪽 상단)을 잡고 나면, 나머지 모양의 위치에 대한 벡터입니다.

아래와 같이 기준점 (a, b)를 두고 나면, 다른 점들의 상대적 위치는 아래와 같이 구할 수 있습니다. 



아래와 같이 상대적 위치를 벡터에 넣었습니다. 



다음으로는 회전과 뒤집기입니다.

각 도형은 회전이나 뒤집기가 가능하기 때문에, 0도, 90도, 180도, 270도 회전에 대한 상태값과 뒤집었을 때의 0도, 90도, 180도, 270도 회전값이 필요합니다. 

뒤집기는 비교적 쉽게 구현이 가능한데, 회전에 대한 것은 다소 헷갈렸습니다.


https://ko.wikipedia.org/wiki/%ED%9A%8C%EC%A0%84%EB%B3%80%ED%99%98%ED%96%89%EB%A0%AC 

위의 링크에서 자세하게 확인 가능합니다. 

함수를 구현 합니다. (소스 코드 참조)


그리고 (0,0) 부터 시작해서, (N-1, M-1) 까지 돌면서 5개 도형의 인덱스를 체크해봅니다.
인덱스를 체크할 때에는 범위가 0~N-1, 0~M-1 안에 들어가는지 확인합니다. 

합을 구하고 나면 최대 합과 비교해서 더 크면 최대 합을 대체합니다. 


다른 풀이들은 dfs 를 많이 사용했던데, 해당 풀이를 참고해 보는 것도 좋을 것 같습니다. 



- 소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <iostream> 
#include <vector>
#pragma warning(disable : 4996)
 
using namespace std;
 
///////////////
// 전역 변수 //
//////////////
#define MAX_NM 500
int N, M;
int answer = -1
 
vector<vector<int>> matrix(MAX_NM);
vector<pair<intint>> shape_1 = { { 0,1 },{ 0,2 },{ 0,3 } };
vector<pair<intint>> shape_2 = { { 0,1 },{ 1,0 },{ 1,1 } };
vector<pair<intint>> shape_3 = { { 1,0 },{ 2,0 },{ 2,1 } };
vector<pair<intint>> shape_4 = { { 1,0 },{ 1,1 },{ 2,1 } };
vector<pair<intint>> shape_5 = { { 0,1 },{ 0,2 },{ 1,1 } };
vector<vector<pair<intint>>> shape_vec = { shape_1 , shape_2 , shape_3 , shape_4 , shape_5 };
 
////////////
// 함수들 //
////////////
 
// 도형 회전 
vector<pair<intint>> rotate(int degree, vector<pair<intint>> shape) {
    vector<pair<intint>> _shape = shape;
    int shape_size = _shape.size();
 
    switch (degree) {
    case 0
        break;
    case 90:
        for (int shp_idx = 0; shp_idx < shape_size; shp_idx++)
            _shape.at(shp_idx) = { ((0)*_shape.at(shp_idx).first + (-1)* _shape.at(shp_idx).second),
                                            ((1)*_shape.at(shp_idx).first + (0)* _shape.at(shp_idx).second)};
        break;
    case 180:
        for (int shp_idx = 0; shp_idx < shape_size; shp_idx++)
            _shape.at(shp_idx) = { ((-1)*_shape.at(shp_idx).first + (0)*_shape.at(shp_idx).second),
                                            ((0)*_shape.at(shp_idx).first + (-1)*_shape.at(shp_idx).second) };
        break;
    case 270:
        for (int shp_idx = 0; shp_idx < shape_size; shp_idx++)
            _shape.at(shp_idx) = { ((0)*_shape.at(shp_idx).first + (1)*_shape.at(shp_idx).second),
                                            ((-1)*_shape.at(shp_idx).first + (0)* _shape.at(shp_idx).second) };
        break;
    default
        printf("error");
        exit(9);
        break;
    }
 
    return _shape;
}
 
// 도형 뒤집기 
vector<pair<intint>> flip(vector<pair<intint>> shape) {
    vector<pair<intint>> _shape = shape;
    int shape_size = _shape.size();
 
    for (int shp_idx = 0; shp_idx < shape_size; shp_idx++)
        _shape.at(shp_idx) = { -(_shape.at(shp_idx).first), (_shape.at(shp_idx).second) };
 
    return _shape;
}
 
// 합 구하기
void shape_sum(vector<pair<intint>> shape, int row, int col) {
    int sum = matrix.at(row).at(col);
    int shape_size = shape.size(); 
 
    for (int shp_idx = 0; shp_idx < shape_size; shp_idx++) {
        int now_row = row + shape.at(shp_idx).first;
        int now_col = col + shape.at(shp_idx).second;
 
        // 인덱스 범위 체크한다. 
        if (now_row < 0 || now_row > N -1)  return;
        if (now_col < 0 || now_col > M - 1return;
 
        // sum 에 추가 
        sum += matrix.at(now_row).at(now_col);
    }
 
    if (sum > answer) answer = sum ;
}
 
 
///////////////
// 메인 함수 //
//////////////
int main() {  
    cin >> N >> M;
 
    // 값 입력받기 
    for ( int row_idx = 0; row_idx < N; row_idx++){
        for (int col_idx = 0; col_idx < M; col_idx++) {
            int sub;    scanf("%d"&sub);
            matrix.at(row_idx).push_back(sub);
        }
    }
 
    // 도형 하나하나 비교해가면서 확인해보기 
    for (int row_idx = 0; row_idx < N; row_idx++) {
        for (int col_idx = 0; col_idx < M; col_idx++) {
 
            // 한 위치에서 5개의 도형을 확인해야 한다. 
            int shape_vec_size = shape_vec.size();
            for (int shp_idx = 0; shp_idx < shape_vec_size; shp_idx++) {
 
                // flip 하기 전 
                for ( int chg_idx = 0 ; chg_idx < 4 ; chg_idx++){
                    vector<pair<intint>> _shape = rotate(chg_idx * 90, shape_vec.at(shp_idx));
                    shape_sum(_shape, row_idx, col_idx);
                }
 
                // flip 한 후  
                for (int chg_idx = 0; chg_idx < 4; chg_idx++) {
                    vector<pair<intint>> _shape = flip(shape_vec.at(shp_idx));
                    _shape = rotate(chg_idx * 90, _shape);
                    shape_sum(_shape, row_idx, col_idx);
                }
                 
            }
             
        }
    } 
 
    cout << answer;
 
    return 0
}
cs