불! (4179번)
https://www.acmicpc.net/problem/4179
풀이방법
- 지훈과 불의 거리 BFS를 이용해 문제를 해결한다.
- 불의 거리를 BFS로 구한다.
- 지훈의 거리를 BFS로 구한다.
- 단, 거리를 구하다가
X
,Y
의 범위에서 벗어날 경우 해당 위치가 정답이 될 가능성이 있다. - 정답이 되기 위해서는 해당 위치에 불이 없어야하므로 범위에서 벗어날 때 불이 있는 자리인지 확인한다.
- 단, 거리를 구하다가
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int y = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
int[][] map = new int[y][x];
int[][] jDist = new int[y][x];
int[][] fDist = new int[y][x];
Queue<int[]> jihoon = new LinkedList<>();
Queue<int[]> fire = new LinkedList<>();
for (int i = 0; i < y; i++) {
StringBuilder str = new StringBuilder(br.readLine());
for (int j = 0; j < x; j++) {
jDist[i][j] = -1;
fDist[i][j] = -1;
if (str.charAt(j) == '#') map[i][j] = 0;
else if (str.charAt(j) == '.') map[i][j] = 1;
else if (str.charAt(j) == 'J') {
jihoon.add(new int[]{i, j});
map[i][j] = 2;
jDist[i][j] = 1;
} else if (str.charAt(j) == 'F') {
fire.add(new int[]{i, j});
map[i][j] = 2;
fDist[i][j] = 1;
}
}
}
int[] directX = {1, 0, -1, 0};
int[] directY = {0, 1, 0, -1};
int dx = 0;
int dy = 0;
int[] cur;
while (!fire.isEmpty()) {
cur = fire.poll();
for (int i = 0; i < 4; i++) {
dx = cur[1] + directX[i];
dy = cur[0] + directY[i];
if (dx < 0 || dx >= x || dy < 0 || dy >= y) continue;
if (map[dy][dx] == 1 && fDist[dy][dx] == -1) {
fDist[dy][dx] = fDist[cur[0]][cur[1]] + 1;
fire.add(new int[]{dy, dx});
}
}
}
while (!jihoon.isEmpty()) {
cur = jihoon.poll();
for (int i = 0; i < 4; i++) {
dx = cur[1] + directX[i];
dy = cur[0] + directY[i];
if ((dx < 0 || dx >= x || dy < 0 || dy >= y)) {
if ((fDist[cur[0]][cur[1]] > jDist[cur[0]][cur[1]]) || fDist[cur[0]][cur[1]] == -1) {
System.out.println(jDist[cur[0]][cur[1]]);
return;
}
continue;
}
if (map[dy][dx] == 1 && jDist[dy][dx] == -1) {
jDist[dy][dx] = jDist[cur[0]][cur[1]] + 1;
jihoon.add(new int[]{dy, dx});
}
}
}
System.out.println("IMPOSSIBLE");
}
}
Comments powered by Disqus.