작심 24/7

[백준] 3055번 탈출 본문

백준

[백준] 3055번 탈출

모닝수박 2020. 6. 16. 18:08
 

3055번: 탈출

문제 사악한 암흑의 군주 이민혁은 드디어 마법 구슬을 손에 넣었고, 그 능력을 실험해보기 위해 근처의 티떱숲에 홍수를 일으키려고 한다. 이 숲에는 고슴도치가 한 마리 살고 있다. 고슴도치��

www.acmicpc.net

백준 문제와 비슷한 문제이다.

모든 홍수 먼저 인접한 빈 곳을 찾아 *로 바꾸어주고

다음 검사를 위해 큐에 넣어준다.

그다음 고슴도치가 갈 수 있는 인접한 빈 곳을 찾아

그곳까지 가는데 걸린 시간 + 1을 넣어준다.

 

고슴도치가 D를 만나면 그때까지의 시간을 출력해주고

만나지 못했다면 KAKTUS를 출력한다.

#include <iostream>
#include <string>
#include <queue>
using namespace std;
char forest[51][51];
queue <pair<int, int>> flood, hedgehog, temp;
int Dx, Dy, success = -1, x, y;
int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 }, visited[51][51] = { 0 }, res[51][51] = { 0 };

void Bfs(int R, int C) {
	while (1) {
		while (!flood.empty()) {
			for (int i = 0; i < 4; i++) {
				x = flood.front().first + dx[i], y = flood.front().second + dy[i];
				if (x >= 0 && x < R && y >= 0 && y < C && (forest[x][y] == '.' || forest[x][y] == 'S')) {
					forest[x][y] = '*';
					temp.push(pair<int, int>(x, y));
				}
			}
			flood.pop();
		}
		while (!temp.empty()) {
			flood.push(pair<int, int>(temp.front().first, temp.front().second));
			temp.pop();
		}
		while (!hedgehog.empty()) {
			for (int i = 0; i < 4; i++) {
				x = hedgehog.front().first + dx[i], y = hedgehog.front().second + dy[i];
				if (x >= 0 && x < R && y >= 0 && y < C && (forest[x][y] == '.' || forest[x][y] == 'D') && visited[x][y] == 0) {
					visited[x][y] = 1;
					res[x][y] = res[hedgehog.front().first][hedgehog.front().second] + 1;
					if (forest[x][y] == 'D') {
						success = res[x][y];
						break;
					}
					temp.push(pair<int, int>(x, y));
				}
			}
			hedgehog.pop();
			if (success != -1) break;
		}
		if (success != -1 || temp.empty()) break;
		while (!temp.empty()) {
			hedgehog.push(pair<int, int>(temp.front().first, temp.front().second));
			temp.pop();
		}
	}
}

int main() {
	int R, C;
	cin >> R >> C;
	string a;
	for (int i = 0; i < R; i++) {
		cin >> a;
		for (int j = 0; j < C; j++) {
			forest[i][j] = a[j];
			if (a[j] == 'S') hedgehog.push(pair<int, int>(i, j));
			else if (a[j] == 'D') Dx = i, Dy = j;
			else if (a[j] == '*') flood.push(pair<int, int>(i, j));
		}
	}

	Bfs(R, C);
	if (success == -1) cout << "KAKTUS\n";
	else cout << success;

	return 0;
}

'백준' 카테고리의 다른 글

[백준] 16397번 탈출 (C++, JAVA)  (0) 2020.06.18
[백준] 2206번 벽 부수고 이동하기 (C++)  (0) 2020.06.16
[백준] 5427번 불 (C++, JAVA)  (0) 2020.06.16
[백준] 6593번 상범 빌딩  (0) 2020.06.16
[백준] 1260번 DFS와 BFS  (2) 2020.06.15
Comments