https://www.acmicpc.net/problem/4179
지훈이는 미로에서 일을 한다. 지훈이를 미로에서 탈출하도록 도와주자!
미로에서의 지훈이의 위치와 불이 붙은 위치를 감안해서 지훈이가 불에 타기전에 탈출할 수 있는지의 여부, 그리고 얼마나 빨리 탈출할 수 있는지를 결정해야한다.
지훈이와 불은 매 분마다 한칸씩 수평또는 수직으로(비스듬하게 이동하지 않는다) 이동한다.
불은 각 지점에서 네 방향으로 확산된다.
지훈이는 미로의 가장자리에 접한 공간에서 탈출할 수 있다.
지훈이와 불은 벽이 있는 공간은 통과하지 못한다.
입력의 첫째 줄에는 공백으로 구분된 두 정수 R과 C가 주어진다. 단, 1 ≤ R, C ≤ 1000 이다. R은 미로 행의 개수, C는 열의 개수이다.
다음 입력으로 R줄동안 각각의 미로 행이 주어진다.
각각의 문자들은 다음을 뜻한다.
#: 벽
.: 지나갈 수 있는 공간
J: 지훈이의 미로에서의 초기위치 (지나갈 수 있는 공간)
F: 불이 난 공간
J는 입력에서 하나만 주어진다.
지훈이가 불이 도달하기 전에 미로를 탈출 할 수 없는 경우 IMPOSSIBLE 을 출력한다.
지훈이가 미로를 탈출할 수 있는 경우에는 가장 빠른 탈출시간을 출력한다.
일반적인 BFS 문제를 푸는 방법에서 visit배열을 하나 더 써서 풀어야한다.
이때, 지훈이는 visit1에서 불이 번진 시간보다 작은 시간에만 해당 위치를 방문할 수 있다. (불이 번지기 전에 도착해야 함)
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
int r, c;
char arr[1001][1001];
int sx, sy; //지훈이 위치
int fx, fy; //불 위치
int visit[1001][1001];
int visit2[1001][1001];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };
int answer = 1000000;
void fireBFS() {
queue<pair<int, int>> q;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (arr[i][j]=='F') {
q.push(pair<int, int>(i, j));
visit[i][j] = 1;
}
}
}
while (!q.empty()) {
pair<int, int> cur;
cur = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = dx[i] + cur.first;
int ny = dy[i] + cur.second;
if (nx >= 0 && ny >= 0 && nx < r && ny < c) {
if (arr[nx][ny] == '.' && visit[nx][ny]==0) {
visit[nx][ny] = visit[cur.first][cur.second] + 1;
q.push(pair<int, int>(nx, ny));
}
}
}
}
}
void jihunBFS() {
queue<pair<int, int>> q;
q.push(pair<int, int>(sx, sy));
visit2[sx][sy] = 1;
while (!q.empty()) {
pair<int, int> cur;
cur = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = dx[i] + cur.first;
int ny = dy[i] + cur.second;
if (nx > 0 && ny > 0 && nx < r-1 && ny < c-1) {
if (arr[nx][ny] == '.' && visit2[nx][ny] == 0) {
if (visit[nx][ny] > visit2[cur.first][cur.second] + 1 || visit[nx][ny]==0) {
visit2[nx][ny] = visit2[cur.first][cur.second] + 1;
q.push(pair<int, int>(nx, ny));
}
}
}
else if (nx == 0 || ny == 0 || nx == r - 1 || ny == c - 1) {
if (arr[nx][ny] == '.' && visit2[nx][ny]==0) {
if (visit[nx][ny] > visit2[cur.first][cur.second] + 1 || visit[nx][ny] == 0) {
visit2[nx][ny] = visit2[cur.first][cur.second] + 1;
answer = min(answer, visit2[nx][ny]);
}
}
}
}
}
}
int main()
{
cin.tie(0);
cout.tie(0);
cin.sync_with_stdio(0);
cin >> r >> c;
for (int i = 0; i < r; i++) {
cin >> arr[i];
for (int j = 0; j < c; j++) {
if (arr[i][j] == 'J') {
sx = i;
sy = j;
}
}
}
if (sx == 0 || sy == 0 || sx == r - 1 || sy == c - 1) {
cout << 1;
return 0;
}
fireBFS();
jihunBFS();
if (answer == 1000000) cout << "IMPOSSIBLE";
else cout << answer;
return 0;
}