#include <iostream>
#include <string>
#include <queue>
#include <algorithm>

using namespace std;
#define X first
#define Y second
string board[1002];
int dist_j[1002][1002];
int fire[1002][1002];

int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n,m;
    queue<pair<int,int>> qf,qj;
    cin >> n >> m;
    for(int i=0; i<n; i++) {
        cin >> board[i];
    }
    for(int i=0; i<n; i++) {
        fill(dist_j[i],dist_j[i]+m,-1);
        fill(fire[i],fire[i]+m,-1);
    }
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            if(board[i][j]=='J') {
                qj.push({i,j});
                dist_j[i][j]=0;
            }
            else if(board[i][j]=='F') {
                qf.push({i,j});
                fire[i][j]=0;
            }
        }
    }
    //불
    while(!qf.empty()) {
        pair<int,int> 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>=n || ny <0 || ny >=m) continue;
             //길이 아니고 방문 됨
            if(board[nx][ny]!='.' || fire[nx][ny]>=0  ) continue;
            qf.push({nx,ny});
            fire[nx][ny]=fire[cur.X][cur.Y]+1;
        }
    }
    while(!qj.empty()) {
        pair<int,int> cur=qj.front();
        qj.pop();
        for(int i=0; i<4; i++) {
            int nx=cur.X+dx[i];
            int ny=cur.Y+dy[i];
            //끝에옴
            if(nx<0 || nx>=n || ny <0 || ny >=m) {
                cout << dist_j[cur.X][cur.Y]+1;
                return 0;
            }
            //벽이거나 이미 방문
            if(board[nx][ny]=='#' || dist_j[nx][ny]>=0) continue;
            //불이 있을때 &&지훈이가 가는 시간이 불이 번지는 시간보다 크거나 같을때
            if(fire[nx][ny]!=-1 && dist_j[cur.X][cur.Y]+1>=fire[nx][ny]) continue;
            
            dist_j[nx][ny]=dist_j[cur.X][cur.Y]+1;
            qj.push({nx,ny});
        }
        
    }
    cout << "IMPOSSIBLE";
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: