package baekjoon;
import java.util.*;
import java.io.*;
public class 불_4179 {
static int R, C;
static char[][] arr;
static int[][] dist1, dist2;
static Queue<Pair> queue1, queue2;
static int[] dr = {-1, 1, 0, 0};
static int[] dc = {0, 0, -1, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
arr = new char[R][C];
dist1 = new int[R][C];
dist2 = new int[R][C];
for (int i = 0; i < R; i++) {
String str = br.readLine();
for (int j = 0; j < C; j++) {
arr[i][j] = str.charAt(j);
dist1[i][j] = -1;
dist2[i][j] = -1;
}
}
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if (arr[i][j] == 'F') {
queue1.add(new Pair(i, j));
dist1[i][j] = 0;
}
if (arr[i][j] == 'J') {
queue2.add(new Pair(i, j));
dist2[i][j] = 0;
}
}
}
//불 bfs
bfs1();
//지훈이 bfs
bfs2();
System.out.println("IMPOSSIBLE");
}
private static void bfs1() {
while(!queue1.isEmpty()){
Pair cur = queue1.poll();
for(int d=0; d<4; d++){
int nr = cur.x+dr[d];
int nc = cur.y+dc[d];
if(nr < 0 || nc < 0 || nr >= R || nc >= C) continue;
if(dist1[nr][nc] >= 0 || arr[nr][nc] == '#') continue;
queue1.add(new Pair(nr, nc));
dist1[nr][nc] = dist1[cur.x][cur.y]+1;
}
}
}
private static void bfs2() {
while(!queue2.isEmpty()){
Pair cur = queue2.poll();
for(int d=0; d<4; d++){
int nr = cur.x+dr[d];
int nc = cur.y+dc[d];
if(nr < 0 || nc < 0 || nr >= R || nc >= C){
System.out.println(dist2[cur.x][cur.y]+1);
return;
}
if(dist2[nr][nc] >= 0 || arr[nr][nc] == '#' ) continue;
if(dist1[nr][nc] != -1 && dist1[nr][nc] <= dist2[nr][nc]) continue;
queue2.add(new Pair(nr,nc));
dist2[nr][nc] = dist2[cur.x][cur.y]+1;
}
}
}
static class Pair{
int x;
int y;
public Pair(int x, int y){
this.x = x;
this.y = y;
}
}
}
댓글남기기