하다보니

1697번-불! 본문

알고리즘 풀이/백준

1697번-불!

claire 2022. 1. 30. 23:03
#include<bits/stdc++.h>
#define X first
#define Y second
using namespace std;

string board[1002];
int dist1[1002][1002];	//불 전파
int dist2[1002][1002];	//지훈이 이동
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };

int main() {
	int r, c;
	cin >> r >> c;
	queue<pair<int, int>> Q1; //불
	queue<pair<int, int>> Q2; //지훈이
	for (int i = 0; i < r; i++) fill(dist1[i], dist1[i] + c,-1);
	for (int i = 0; i < r; i++)fill(dist2[i], dist2[i] + c, -1);
	for (int i = 0; i < r; i++) {
		cin >> board[i];
	}
	//전체 배열을 돌며 불의 위치와 지훈이의 초기 위치를 구한다. 
	for (int i = 0; i < r; i++) {
		for (int j = 0; j < c; j++) {
			if (board[i][j] == 'F') {
				Q1.push({ i,j });
				dist1[i][j] = 0;
			}
			if (board[i][j] == 'J') {
				Q2.push({ i,j });
				dist2[i][j] = 0;
			}
		}
	}
	while (!Q1.empty()) {
		auto cur = Q1.front(); Q1.pop();
		for (int i = 0; i < 4; i ++ ) {
			int nx = cur.X + dx[i];
			int ny = cur.Y + dy[i];
			if (nx < 0 || nx >= r || ny < 0 || ny >= c)continue;
			if (dist1[nx][ny] >= 0 || board[nx][ny] == '#')continue;
			dist1[nx][ny] = dist1[cur.X][cur.Y] + 1;
			Q1.push({ nx,ny });
		}
	}
	while (!Q2.empty()) {
		auto cur = Q2.front(); Q2.pop();
		for (int i = 0; i < 4; i++) {
			int nx = cur.X + dx[i];
			int ny = cur.Y + dy[i];
			if (nx < 0 || nx >= r || ny < 0 || ny >= c) {
				cout << dist2[cur.X][cur.Y] + 1;
				return 0;
			}
			if (dist2[nx][ny] >= 0 || board[nx][ny] == '#')continue;
			if (dist1[nx][ny] != -1 && dist1[nx][ny] <= dist2[cur.X][cur.Y] + 1)continue;
			dist2[nx][ny] = dist2[cur.X][cur.Y] + 1;
			Q2.push({ nx,ny });
		}
	}
	cout << "IMPOSSIBLE";
}

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

1012번-유기농 배추  (0) 2022.02.03
1697번-숨바꼭질  (0) 2022.02.03
7576번-토마토  (0) 2022.01.29
2178번-미로탐색  (0) 2022.01.29
1926번-그림  (0) 2022.01.26