BOJ

[백준] 14500번 테트로미노 - C++

브루트포스,DFS

Posted by dongjune on October 6, 2020

문제

14500번 테트로미노

풀이

ㅜ 모양을 제외하면 모두 depth가 3인 DFS로 탐색할 수 있는 모양이다.
14500-1

반복문으로 NxM 배열의 모든 정점을 탐색하며 DFS를 수행하여 최대값을 갱신했고, DFS를 사용할 수 없는 ㅜ의 4가지 방향 ㅜ,ㅏ,ㅗ,ㅓ 모양은 따로 처리했다.

코드

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
#include <iostream>
#include <algorithm>

using namespace std;

int dy[] = {0, 0, -1, 1};
int dx[] = {-1, 1, 0, 0};

int board[500][500], visit[500][500];
int MAX;
int N, M;

// ㅜ모양 체크
void findFuckShapeMax(int y, int x)
{
    // ㅜ
    if (y + 1 < N && x + 2 < M)
        MAX = max(MAX, board[y][x] + board[y][x + 1] + board[y][x + 2] + board[y + 1][x + 1]);
    // ㅏ
    if (y + 2 < N && x + 1 < M)
        MAX = max(MAX, board[y][x] + board[y + 1][x] + board[y + 1][x + 1] + board[y + 2][x]);
    // ㅗ
    if (y - 1 >= 0 && x + 2 < M)
        MAX = max(MAX, board[y][x] + board[y][x + 1] + board[y][x + 2] + board[y - 1][x + 1]);
    // ㅓ
    if (y + 2 < N && x - 1 >= 0)
        MAX = max(MAX, board[y][x] + board[y + 1][x] + board[y + 1][x - 1] + board[y + 2][x]);
}

// ㅜ모양 외 체크
void findNormalMax(int L, int sum, int y, int x)
{
    if (L == 3)
    {
        MAX = max(MAX, sum);
        return;
    }
    for (int i = 0; i < 4; i++)
    {
        int ny = y + dy[i], nx = x + dx[i];
        if (ny < 0 || nx < 0 || ny >= N || nx >= M)
            continue;
        if (visit[ny][nx])
            continue;
        visit[ny][nx] = true;
        findNormalMax(L + 1, sum + board[ny][nx], ny, nx);
        visit[ny][nx] = false;
    }
}

void findMax(int y, int x)
{
    findFuckShapeMax(y, x);

    visit[y][x] = true;
    findNormalMax(0, board[y][x], y, x);
    visit[y][x] = false;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    // 입력받기
    cin >> N >> M;
    for (int i = 0; i < N; i++)
        for (int j = 0; j < M; j++)
            cin >> board[i][j];

    // 모든 정점마다 테트로미노 합의 최대값 찾기
    for (int i = 0; i < N; i++)
        for (int j = 0; j < M; j++)
            findMax(i, j);

    cout << MAX << '\n';

    return 0;
}