본문 바로가기
알고리즘/BOJ(백준)

[ 백준-14502번 / 완전탐색 ] 연구소 (삼성기출)

by 뎁꼼 2020. 3. 12.

1. 문제


 

14502번: 연구소

인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다. 연구소는 크기가 N×M인 직사각형으로 나타낼 수 있으며, 직사각형은 1×1 크기의 정사각형으로 나누어져 있다. 연구소는 빈 칸, 벽으로 이루어져 있으며, 벽은 칸 하나를 가득 차지한다.  일부 칸은 바이러스가 존재하며, 이 바이러스는 상하좌우로 인접한 빈 칸으로 모두 퍼져나갈 수 있다.

www.acmicpc.net

연구소

시간 제한메모리 제한제출정답맞은 사람정답 비율

2 초 512 MB 25402 14557 8036 54.820%

문제

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

연구소는 크기가 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개 이상이다.

출력

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

예제 입력 1 복사

7 7 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

예제 출력 1 복사

27

예제 입력 2 복사

4 6 0 0 0 0 0 0 1 0 0 0 0 2 1 1 1 0 0 2 0 0 0 0 0 2

예제 출력 2 복사

9

 

 

 

 

2. 소스코드


1회차 - 20/03/12

 

- 2중 for문, 중복제거 없음. 300ms

더보기
#include <cstdio>
#include <cstring>
#include <queue>

#pragma warning (disable : 4996);

using namespace std;

int n, m, maximum = 0;
int map[8][8];
int visited[8][8];

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

vector<pair<int, int>> virusPos;

void check(int map_bfs[][8]) {
	int ans = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (map_bfs[i][j] == 0) ans++;
		}
	}
	if (ans > maximum) maximum = ans;
}

void bfs(int map_bfs[][8], pair<int, int> start) {

	queue<pair<int, int>> q;
	q.push(start);
	while (!q.empty()) {
		int y = q.front().first;
		int x = q.front().second;
		q.pop();
		visited[y][x] = 1;
		for (int i = 0; i < 4; i++) {
			int ny = y + dy[i];
			int nx = x + dx[i];
			if (ny < 0 || nx < 0 || ny >= n || nx >= m) continue;
			else if (map_bfs[ny][nx] == 0 && !visited[ny][nx]) {
				map_bfs[ny][nx] = 2;
				q.push(make_pair(ny, nx));
			}
		}
	}	
}

void dfs(int cnt) {

	if (cnt == 4) {
		int map_bfs[8][8];
		memcpy(map_bfs, map, sizeof(map_bfs));
		for (int i = 0; i < virusPos.size(); i++) {
			bfs(map_bfs, virusPos[i]);
		}
		check(map_bfs);
		memset(visited, 0, sizeof(visited));
		return;
	}

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (map[i][j] == 0) {
				map[i][j] = 1;
				dfs(cnt + 1);
				map[i][j] = 0;
			}
		}
	}
	/*int copyMap[8][8];
	memcpy(copyMap, input, sizeof(copyMap));

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (copyMap[i][j] == 0) {
				copyMap[i][j] = 1;
				dfs(copyMap, cnt + 1);
				copyMap[i][j] = 0;
			}
		}
	}*/
	return;
}

int main() {
	scanf("%d %d", &n, &m);
	
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			scanf("%d", &map[i][j]);
			if (map[i][j] == 2) {
				virusPos.push_back(make_pair(i,j));
			}
		}
	}
	dfs(1);
	printf("%d", maximum);
}

 

 

- next_permutation 이용 : 60ms

더보기
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

#pragma warning (disable : 4996);

using namespace std;

int n, m, maximum = 0;
int map[8][8];
int visited[8][8];

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

vector<pair<int, int>> virusPos;
vector<pair<int, int>> emptyPos;
vector<int> idx;

void check(int map_bfs[][8]) {
	int ans = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (map_bfs[i][j] == 0) ans++;
		}
	}
	if (ans > maximum) maximum = ans;
}

void bfs(int map_bfs[][8], pair<int, int> start) {
	queue<pair<int, int>> q;
	q.push(start);
	while (!q.empty()) {
		int y = q.front().first;
		int x = q.front().second;
		q.pop();
		visited[y][x] = 1;
		for (int i = 0; i < 4; i++) {
			int ny = y + dy[i];
			int nx = x + dx[i];
			if (ny < 0 || nx < 0 || ny >= n || nx >= m) continue;
			else if (map_bfs[ny][nx] == 0 && !visited[ny][nx]) {
				map_bfs[ny][nx] = 2;
				q.push(make_pair(ny, nx));
			}
		}
	}
}

void dfs(int cnt) {
	do {
		vector<pair<int, int>> temp;
		int cnt = 0;
		for (int i = 0; i < emptyPos.size(); i++) {
			if (idx[i]) {
				map[emptyPos[i].first][emptyPos[i].second] = 1;
				temp.push_back(make_pair(emptyPos[i].first, emptyPos[i].second));
				cnt++;
				if (cnt == 3) break;
			}
		}
		int map_bfs[8][8];
		memcpy(map_bfs, map, sizeof(map_bfs));
		for (int i = 0; i < virusPos.size(); i++) {
			bfs(map_bfs, virusPos[i]);
		}
		check(map_bfs);
		memset(visited, 0, sizeof(visited));

		for (int i = 0; i < temp.size(); i++) {
			map[temp[i].first][temp[i].second] = 0;
		}
		temp.clear();
	} while (next_permutation(idx.begin(), idx.end()));
	return;
}

int main() {
	scanf("%d %d", &n, &m);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			scanf("%d", &map[i][j]);
			if (map[i][j] == 2) {
				virusPos.push_back(make_pair(i, j));
			}
			else if (map[i][j] == 0) {
				emptyPos.push_back(make_pair(i, j));
			}
		}
	}
	for (int i = 0; i < emptyPos.size() - 3; i++) {
		idx.push_back(0);
	}
    	for (int i = 0; i < 3; i++) {
		idx.push_back(1);
	}
	dfs(1);
	printf("%d", maximum);
}

 

 

2회차 - 20/05/12

 

- 2중 for문 중복 제거, 48ms

- dfs로 벽을 3개 세우고, bfs로 바이러스를 퍼트리는 컨셉은 1회차와 동일. 다만 코드가 조금 더 깔끔해졌고 안전지대 값을 2중 포문이 아닌, 단순 사칙연산으로 계산함.

 

#include <cstdio>
#include <queue>
#define MAX 8
#define WALL 1
#define VR 2
using namespace std;
struct Info
{
    int map[MAX][MAX];
    int preX, preY;

}info;

queue<pair<int, int>> vrPos;
int n, m, cntWall, ans;
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };


int bfs(Info info) {
    int cnt = 0;
    int visited[MAX][MAX] = { 0, };
    queue<pair<int, int>> temp = vrPos;
    while (!temp.empty())
    {
        auto cur = temp.front(); temp.pop();
        ++cnt;
        for (int i = 0; i < 4; ++i) {
            int nx = cur.first + dx[i];
            int ny = cur.second + dy[i];
            if (nx >= n or ny >= m or nx < 0 or ny < 0) continue;
            if (visited[nx][ny] == 1 or info.map[nx][ny] != 0) continue;
            temp.push({ nx,ny });
            info.map[nx][ny] = VR;
            visited[nx][ny] = 1;
        }
    }
    return (n * m) - (cntWall + 3) - cnt; 
}

void dfs(Info info, int depth) { 
    if (depth == 3) {
        int res = bfs(info);
        if (res > ans) ans = res;
        return;
    }
    for (int i = info.preX; i < n; ++i){
        for (int j = info.preY; j < m; ++j) {
            if (info.map[i][j] == 0) {
                info.map[i][j] = WALL;
                info.preX = i;
                info.preY = j;
                dfs(info, depth + 1);
                info.map[i][j] = 0;
            }
        }
        info.preY = 0;
    }
    return;
}
 
int main() {
    scanf("%d %d", &n, &m);
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < m; ++j){
            scanf("%d", &info.map[i][j]);
            if (info.map[i][j] == VR) vrPos.push({ i,j });
            if (info.map[i][j] == WALL) ++cntWall;
        }
    dfs(info, 0);
    printf("%d", ans);
    return 0;
}