본문 바로가기
백준 알고리즘/BFS

백준 3055번 C++

by paysmile 2019. 8. 14.

#include <iostream>
#include <cstring>
#include <string>
#include <queue>

using namespace std;
const int MAX = 51;
string map[MAX];
int r, c;
queue<pair<int, int>> water,moves;
pair<int, int> room;
int visited2[MAX][MAX];

struct Move {
	int x, y;
};
Move mv[4] = { {1,0},{-1,0},{0,1},{0,-1} };

int bfs() {

	while (!moves.empty()) {

		int watersize = water.size();
		for (int i = 0; i < watersize; i++) {
			int currenti = water.front().first;
			int currentj = water.front().second;
			water.pop();

			for (int k = 0; k < 4; k++) {
				int movei = currenti + mv[k].x;
				int movej = currentj + mv[k].y;

				if (movei >= 0 && movei < r && movej >= 0 && movej < c) {
					if (map[movei][movej] == '.') {
						water.push(make_pair(movei, movej));
						map[movei][movej] = '*';
					}
				}
			}
		}
		
		int movesize = moves.size();
		for (int i = 0; i < movesize; i++) {
			int currenti = moves.front().first;
			int currentj = moves.front().second;
			moves.pop();

			if (make_pair(currenti, currentj) == room)
				return visited2[currenti][currentj]+1;

			for (int k = 0; k < 4; k++) {
				int movei = currenti + mv[k].x;
				int movej = currentj + mv[k].y;

				if (movei >= 0 && movei < r && movej >= 0 && movej < c) {
					if (map[movei][movej] != '*' && map[movei][movej] != 'X' && visited2[movei][movej] == -1) {
						moves.push(make_pair(movei, movej));
						visited2[movei][movej] = visited2[currenti][currentj] + 1;
					}
				}
			}

		}
	}
	return -1;
}

int main(void) {
	cin >> r >> c;

	memset(visited2, -1, sizeof(visited2));
	for (int i = 0; i < r; i++) {
		cin >> map[i];
		for (int j = 0; j < c; j++) {
			if (map[i][j] == 'S')
				moves.push(make_pair(i, j));
			if (map[i][j] == 'D')
				room = make_pair(i, j);
			if (map[i][j] == '*')
				water.push(make_pair(i, j));
		}
	}
	int answer = bfs();
	if (answer == -1)
		cout << "KAKTUS" << endl;
	else
		cout << answer << endl;
	return 0;
}

'백준 알고리즘 > BFS' 카테고리의 다른 글

백준 2573번 C++  (0) 2019.08.15
백준 2206번 C++  (0) 2019.08.15
백준 1707번 C++  (0) 2019.08.14
백준 5014번 C++  (0) 2019.08.12
백준 2589번 C++  (0) 2019.08.12