반응형
틀렸을 때 참고한 반례입니다.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] dx = new int[]{1, 0, -1 ,0};
int[] dy = new int[]{0, 1, 0, -1};
ArrayList<int[]> FIRE = new ArrayList<>();
ArrayList<int[]> JIHOON = new ArrayList<>();
int[] rc = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int R = rc[0], C = rc[1];
String[][] field = new String[R][C];
int[][] Fdist = new int[R][C];
int[][] Jdist = new int[R][C];
for (int i=0; i<R; i++) {
field[i] = br.readLine().split("");
Arrays.fill(Fdist[i], -1);
Arrays.fill(Jdist[i], -1);
for (int j=0; j<C; j++) {
if (field[i][j].equals("F")) {
FIRE.add(new int[]{i, j});
Fdist[i][j] = 0;
}
if (field[i][j].equals("J")) {
JIHOON.add(new int[]{i, j});
Jdist[i][j] = 0;
}
}
}
while(!FIRE.isEmpty()){
int[] cur = FIRE.remove(0);
for (int dir=0; dir<4; dir++){
int nx = cur[1] + dx[dir];
int ny = cur[0] + dy[dir];
if (nx<0 || nx>=C || ny<0 || ny>=R) continue;
if (Fdist[ny][nx]>=0 || field[ny][nx].equals("#")) continue;
Fdist[ny][nx] = Fdist[cur[0]][cur[1]]+1;
FIRE.add(new int[]{ny, nx});
}
}
while (!JIHOON.isEmpty()){
int[] cur = JIHOON.remove(0);
for (int dir=0; dir<4; dir++){
int nx = cur[1] + dx[dir];
int ny = cur[0] + dy[dir];
if (nx<0 || nx>=C || ny<0 || ny>=R){
System.out.print(Jdist[cur[0]][cur[1]]+1);
System.exit(0);
}
if (Jdist[ny][nx]>=0 || field[ny][nx].equals("#")) continue;
if (Fdist[ny][nx]!=-1 && Fdist[ny][nx] <= Jdist[cur[0]][cur[1]]+1) continue;
Jdist[ny][nx] = Jdist[cur[0]][cur[1]] + 1;
JIHOON.add(new int[]{ny, nx});
}
}
System.out.print("IMPOSSIBLE");
}
}
반응형
'Algorithm' 카테고리의 다른 글
백준 1012번 유기농 배추 [ Java ] (0) | 2021.01.01 |
---|---|
백준 1697번 숨바꼭질 [ Java ] (0) | 2020.12.31 |
백준 11656번 접미사 배열 [ Java ] (0) | 2020.12.30 |
백준 7576번 토마토 [ Java ] (0) | 2020.12.30 |
백준 2178번 미로 탐색 [ Java ] (0) | 2020.12.29 |