https://www.acmicpc.net/problem/4179
BFS ์์ฉ ๋ฌธ์ ๋ค. ์์ ์ ์ด์ ๋น์ทํ ๋ฌธ์ ๋ฅผ ํผ ์ ์ด ์๋๋ฐ ์ง๊ธ๋ณด๋ ์ฝ๋ ๋ก์ง์ด ๋นํจ์จ์ ์ธ ๊ฒ ๊ฐ์์ ๋ ํจ์จ์ ์ธ ๋ฐฉ์์ผ๋ก ํ์ดํ๋ค.
๐์ต๋๊ฐ ์ด๊ธฐํํ ๋, limit.h
ํค๋ INT_MAX
๊ฐ ์ด์ฉ
๐ํ๋ฅผ ๋ฌด์กฐ๊ฑด pair ํํ๋ก ํ ๊ฒ ์๋๋ผ, ๊ตฌ์กฐ์ฒด ๋ง๋ค์ด์ ๊ตฌ์กฐ์ฒด ํ ์ ์ธ
ํ๋ฉด ์ฝ๋๊ฐ ๋ ๊น๋ํจ
#include <iostream>
#include <queue>
#include <limits.h>
using namespace std;
int R, C;
int fire[1001][1001];
char map[1001][1001];
bool visited[1001][1001];
queue<pair<int, int>> fire_q;
int mark = 0;
int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };
struct moves {
int x;
int y;
int cnt;
};
void f_bfs() {
while (!fire_q.empty()) {
int xx = fire_q.front().first;
int yy = fire_q.front().second;
fire_q.pop();
for (int i = 0; i < 4; i++) {
int nx = xx + dx[i];
int ny = yy + dy[i];
if (nx < 0 || nx >= R || ny < 0 || ny >= C || map[nx][ny] == '#') continue;
if (fire[nx][ny] > fire[xx][yy] + 1) {
fire[nx][ny] = fire[xx][yy] + 1;
fire_q.push({ nx, ny });
}
}
}
}
void j_bfs(int x, int y) {
visited[x][y] = true;
queue<moves> q;
q.push({ x, y });
while (!q.empty()) {
int xx = q.front().x;
int yy = q.front().y;
int cnt = q.front().cnt;
q.pop();
if (xx == 0 || xx == R - 1 || yy == 0 || yy == C - 1) {
cout << cnt + 1;
mark = 1;
return;
}
for (int i = 0; i < 4; i++) {
int nx = xx + dx[i];
int ny = yy + dy[i];
if (nx < 0 || nx >= R || ny < 0 || ny >= C || map[nx][ny] == '#' || visited[nx][ny]) continue;
if (fire[nx][ny] > cnt + 1) {
visited[nx][ny] = true;
q.push({ nx, ny, cnt+1 });
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int sx = 0, sy = 0;
cin >> R >> C;
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
fire[i][j] =INT_MAX;
cin >> map[i][j];
if (map[i][j] == 'J') {
sx = i;
sy = j;
}
else if (map[i][j] == 'F') {
fire_q.push({ i, j });
fire[i][j] = 0;
}
}
}
f_bfs();
j_bfs(sx, sy);
if(mark == 0)
cout << "IMPOSSIBLE";
return 0;
}