하다보니

5427번-불 본문

알고리즘 풀이/백준

5427번-불

claire 2022. 2. 8. 10:16
#include<bits/stdc++.h>
#define X first
#define Y second
using namespace std;

int board[1002][1002];
int dist_f[1002][1002];
int dist_s[1002][1002];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	int n;
	cin >> n;
	while (n--) {
		queue<pair<int, int>> Qf = {};
		queue<pair<int, int>> Qs = {};
		bool flag = false;
		int w, h;
		cin >> w >> h;
		for (int i = 0; i < h; i++) {
			fill(dist_f[i], dist_f[i] + w, 0);
			fill(dist_s[i], dist_s[i] + w, 0);
		}
		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				char c;
				cin >> c;
				if (c == '#') {
					board[i][j] = -1;
				}
				else {
					if (c == '*') {
						Qf.push({ i,j });
						dist_f[i][j] = 1;
					}
					else if (c == '@') {
						Qs.push({ i,j });
						dist_s[i][j] = 1;
					}
					board[i][j] = 0;
				}

			}
		}
		while (!Qf.empty()) {
			auto cur = Qf.front(); Qf.pop();
			for (int i = 0; i < 4; i++) {
				int nx = cur.X + dx[i];
				int ny = cur.Y + dy[i];
				if (nx < 0 || nx >= h || ny < 0 || ny >= w)continue;
				if (board[nx][ny] == -1 || dist_f[nx][ny] > 0)continue;

				dist_f[nx][ny] = dist_f[cur.X][cur.Y] + 1;
				Qf.push({ nx,ny });
			}
		}
		while ((!Qs.empty()) && (!flag)) {
			auto cur = Qs.front(); Qs.pop();
			for (int i = 0; i < 4; i++) {
				int nx = cur.X + dx[i];
				int ny = cur.Y + dy[i];
				if (nx < 0 || nx >= h || ny < 0 || ny >= w) {
					cout << dist_s[cur.X][cur.Y] << "\n";
					flag = true;
					break;
				}
				if (board[nx][ny] == -1 || dist_s[nx][ny] > 0)continue;
				if (dist_f[nx][ny] != 0 && dist_f[nx][ny] <= dist_s[cur.X][cur.Y] + 1)continue;
				dist_s[nx][ny] = dist_s[cur.X][cur.Y] + 1;
				Qs.push({ nx,ny });
			}
		}
		if (!flag)cout << "IMPOSSIBLE" << "\n";
	}
}

제발 꼼꼼하게...!!

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

11729번-하노이 탑 이동 순서  (0) 2022.02.08
5014번-스타트링크  (0) 2022.02.08
1629-곱셈  (0) 2022.02.07
2583번-영역 구하기  (0) 2022.02.07
7562번-나이트의 이동  (0) 2022.02.05