백준 4179
#include<bits/stdc++.h>
#define INF 987654321
using namespace std;
int r, c;
int ans = INF;
string arr[1001];
int vis[1001][1001];
int vis1[1001][1001];
int dx[4] = { -1,0,1,0 };
int dy[4] = { 0,1,0,-1 };
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cin >> r >> c;
queue<pair<int, int>> q;
queue<pair<int, int>> q1;
fill(&vis[0][0], &vis[r - 1][c], -1);
for (int i = 0; i < r; i++) {
cin >> arr[i];
for (int j = 0; j < c; j++) {
if (arr[i][j] == 'J') {
q.push({ i,j });
vis[i][j] = 1;
}
if (arr[i][j] == 'F') {
q1.push({ i,j });
vis1[i][j] = 1;
}
}
}
while (!q.empty()) {
pair<int, int> nxt = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = nxt.first + dx[i];
int ny = nxt.second + dy[i];
if (nx < 0 || ny < 0 || nx >= r || ny >= c) continue;
if (arr[nx][ny] == '.' && vis[nx][ny]==-1) {
q.push({ nx,ny });
vis[nx][ny] = vis[nxt.first][nxt.second] + 1;
}
}
}
while (!q1.empty()) {
pair<int, int> nxt = q1.front();
q1.pop();
for (int i = 0; i < 4; i++) {
int nx = nxt.first + dx[i];
int ny = nxt.second + dy[i];
if (nx < 0 || ny < 0 || nx >= r || ny >= c) continue;
if (arr[nx][ny] == '.' && !vis1[nx][ny]) {
vis1[nx][ny] = vis1[nxt.first][nxt.second] + 1;
q1.push({ nx,ny });
if (vis[nx][ny] >= vis1[nx][ny]) vis[nx][ny] = -1;
}
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (i != 0 && i != r - 1 && j != 0 && j != c - 1) continue;
if (vis[i][j] != -1) ans = min(ans, vis[i][j]);
}
}
if (ans==INF) cout << "IMPOSSIBLE" << '\n';
else cout << ans << '\n';
}