Skip to content

Commit 5976e34

Browse files
authored
Merge pull request #211 from AlgorithmWithGod/03do-new30
[20250306] BOJ / G3 / 불! / 신동윤
2 parents b584777 + 1b86b60 commit 5976e34

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
public class Main {
5+
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static int R, C;
8+
static char[][] arr;
9+
static int[][] fireTime;
10+
static int[] dr = {0, 0, -1, 1};
11+
static int[] dc = {-1, 1, 0, 0};
12+
13+
public static void main(String[] args) throws IOException{
14+
15+
input();
16+
setFireTime();
17+
int result = bfs();
18+
System.out.println(result == -1 ? "IMPOSSIBLE" : result);
19+
20+
}
21+
22+
static int bfs() {
23+
int[][] time = new int[R][C];
24+
Queue<int[]> q = new ArrayDeque<>();
25+
for (int i = 0; i < R; i++) {
26+
for (int j = 0; j < C; j++) {
27+
if (arr[i][j] == 'J') {
28+
time[i][j] = 0;
29+
q.offer(new int[] {i, j});
30+
} else {
31+
time[i][j] = -1;
32+
}
33+
}
34+
}
35+
36+
while (!q.isEmpty()) {
37+
int[] tmp = q.poll();
38+
int r = tmp[0];
39+
int c = tmp[1];
40+
for (int i = 0; i < 4; i++) {
41+
int nr = r + dr[i];
42+
int nc = c + dc[i];
43+
if (nr < 0 || nr >= R || nc < 0 || nc >= C) {
44+
// 탈출
45+
return time[r][c] + 1;
46+
}
47+
if (arr[nr][nc] != '.') { continue; }
48+
if (time[nr][nc] > -1) { continue; }
49+
// 불이 번진 시간보다 작아야 해당 칸으로 이동할 수 있다.
50+
if (fireTime[nr][nc] == -1 || fireTime[nr][nc] > time[r][c] + 1) {
51+
time[nr][nc] = time[r][c] + 1;
52+
q.offer(new int[] {nr, nc});
53+
}
54+
}
55+
}
56+
return -1;
57+
}
58+
59+
static void setFireTime( ) { // 불이 번지는 시간을 기록한다.
60+
fireTime = new int[R][C];
61+
Queue<int[]> q = new ArrayDeque<>();
62+
for (int i = 0; i < R; i++) {
63+
for (int j = 0; j < C; j++) {
64+
if (arr[i][j] == 'F') {
65+
q.offer(new int[] {i, j});
66+
fireTime[i][j] = 0;
67+
} else {
68+
fireTime[i][j] = -1;
69+
}
70+
}
71+
}
72+
while (!q.isEmpty()) {
73+
int[] tmp = q.poll();
74+
int r = tmp[0];
75+
int c = tmp[1];
76+
for (int i = 0; i < 4; i++) {
77+
int nr = r + dr[i];
78+
int nc = c + dc[i];
79+
if (nr < 0 || nr >= R || nc < 0 || nc >= C) { continue; }
80+
if (arr[nr][nc] == '#') { continue; }
81+
if (fireTime[nr][nc] > -1) { continue; }
82+
fireTime[nr][nc] = fireTime[r][c] + 1;
83+
q.offer(new int[] {nr, nc});
84+
}
85+
}
86+
}
87+
88+
static void input() throws IOException {
89+
StringTokenizer st = new StringTokenizer(br.readLine());
90+
R = Integer.parseInt(st.nextToken());
91+
C = Integer.parseInt(st.nextToken());
92+
arr = new char[R][C];
93+
for (int i = 0; i < R; i++) {
94+
arr[i] = br.readLine().toCharArray();
95+
}
96+
br.close();
97+
}
98+
99+
}
100+
```

0 commit comments

Comments
 (0)