← Back to Blog

[백준 14502번 | C++] 연구소

computer-science > problem-solving

2026-03-062 min read

#development #cpp #cs #problem-solving #brute-force #graph

출처: 연구소

시간 제한메모리 제한
2 초512 MiB

문제

인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다.

연구소는 크기가 N×M인 직사각형으로 나타낼 수 있으며, 직사각형은 1×1 크기의 정사각형으로 나누어져 있다. 연구소는 빈 칸, 벽으로 이루어져 있으며, 벽은 칸 하나를 가득 차지한다.

일부 칸은 바이러스가 존재하며, 이 바이러스는 상하좌우로 인접한 빈 칸으로 모두 퍼져나갈 수 있다. 새로 세울 수 있는 벽의 개수는 3개이며, 꼭 3개를 세워야 한다.

예를 들어, 아래와 같이 연구소가 생긴 경우를 살펴보자.

2 0 0 0 1 1 0
0 0 1 0 1 2 0
0 1 1 0 1 0 0
0 1 0 0 0 0 0
0 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0

이때, 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 곳이다. 아무런 벽을 세우지 않는다면, 바이러스는 모든 빈 칸으로 퍼져나갈 수 있다.

2행 1열, 1행 2열, 4행 6열에 벽을 세운다면 지도의 모양은 아래와 같아지게 된다.

2 1 0 0 1 1 0
1 0 1 0 1 2 0
0 1 1 0 1 0 0
0 1 0 0 0 1 0
0 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0

바이러스가 퍼진 뒤의 모습은 아래와 같아진다.

2 1 0 0 1 1 2
1 0 1 0 1 2 2
0 1 1 0 1 2 2
0 1 0 0 0 1 2
0 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0

벽을 3개 세운 뒤, 바이러스가 퍼질 수 없는 곳을 안전 영역이라고 한다. 위의 지도에서 안전 영역의 크기는 27이다.

연구소의 지도가 주어졌을 때 얻을 수 있는 안전 영역 크기의 최댓값을 구하는 프로그램을 작성하시오.

입력

첫째 줄에 지도의 세로 크기 N과 가로 크기 M이 주어진다. (3 ≤ N, M ≤ 8)

둘째 줄부터 N개의 줄에 지도의 모양이 주어진다. 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 위치이다. 2의 개수는 2보다 크거나 같고, 10보다 작거나 같은 자연수이다.

빈 칸의 개수는 3개 이상이다.

출력

첫째 줄에 얻을 수 있는 안전 영역의 최대 크기를 출력한다.

풀이

알고리듬 작성에 앞서, graph 시각화 및 문제 정답 관련 유틸함수를 구현했다.

void print_graph(int graph[][8]) {
    cout << "================" << '\n';
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            cout << graph[i][j] << ' ';
        }
        cout << '\n';
    }
}
int count_safe(int graph[][8]) {
    int cnt = 0;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (graph[i][j] == 0)
                ++cnt;
        }
    }
    return cnt;
}

문제를 읽어보면 바이러스가 퍼지는 부분을 먼저 구현해야 된다.
필자는 익숙한 BFS(Breadth-First Search) 알고리듬으로 만들었다.

void spread_virus(int graph[][8], int x, int y) {
    int dx[4] = {1, -1, 0, 0};
    int dy[4] = {0, 0, 1, -1};

    for (int i = 0; i < 4; ++i) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue;
        if (graph[nx][ny] != 0) continue;

        graph[nx][ny] = 2;
        spread_virus(graph, nx, ny);
    }
}

여기까지 왔으면 바이러스가 퍼지는 부분 확인 가능하고, 이제 벽을 세우면 된다.
필자는 DP(Dynamic Programming)으로 이를 구현했다.

모든 경우의 수에 대하여 다음 로직을 수행하면 된다.

로직

  1. 3개의 벽을 설치한다.
  2. 바이러스를 퍼뜨린다.
  3. 안전구역 영역을 확인한다.

위 로직은 수행할 때마다 독립적이여야 하기 때문에 깊은 복사를 수행해야 된다.

void copy_graph(int src[][8], int dst[][8]) {
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            dst[i][j] = src[i][j];
        }
    }
}

int dist = 0;
void place_walls(int graph[][8], int placed) {
    if (placed == 3) {
        int temp[8][8];
        copy_graph(graph, temp);

        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                if (temp[i][j] == 2) {
                    spread_virus(temp, i, j);
                }
            }
        }

        dist = max(dist, count_safe(temp));
        return;
    }

    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (graph[i][j] == 0) {
                graph[i][j] = 1;
                place_walls(graph, placed + 1);
                graph[i][j] = 0;
            }
        }
    }
}

전체 코드

// 14502
#include <iostream>
#include <queue>
#include <utility>
#include <algorithm>
using namespace std;

int N, M;

void print_graph(int graph[][8]) {
    cout << "================" << '\n';
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            cout << graph[i][j] << ' ';
        }
        cout << '\n';
    }
}

void copy_graph(int src[][8], int dst[][8]) {
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            dst[i][j] = src[i][j];
        }
    }
}

void spread_virus(int graph[][8], int x, int y) {
    int dx[4] = {1, -1, 0, 0};
    int dy[4] = {0, 0, 1, -1};

    for (int i = 0; i < 4; ++i) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue;
        if (graph[nx][ny] != 0) continue;

        graph[nx][ny] = 2;
        spread_virus(graph, nx, ny);
    }
}

int count_safe(int graph[][8]) {
    int cnt = 0;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (graph[i][j] == 0)
                ++cnt;
        }
    }
    return cnt;
}

int dist = 0;
void place_walls(int graph[][8], int placed) {
    if (placed == 3) {
        int temp[8][8];
        copy_graph(graph, temp);

        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                if (temp[i][j] == 2) {
                    spread_virus(temp, i, j);
                }
            }
        }

        dist = max(dist, count_safe(temp));
        return;
    }

    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (graph[i][j] == 0) {
                graph[i][j] = 1;
                place_walls(graph, placed + 1);
                graph[i][j] = 0;
            }
        }
    }
}

int main() {
    int x, y;
    int graph[8][8];
    cin >> N >> M;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            cin >> graph[i][j];
        }
    }

    place_walls(graph, 0);

    cout << dist << '\n';

    return 0;
}