Skip to content

Commit aa48c41

Browse files
authored
Merge pull request #1361 from AlgorithmWithGod/JHLEE325
[20251109] BOJ / G3 / 치즈 / 이준희
2 parents 5228254 + d531e6c commit aa48c41

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static int N, M;
7+
static int[][] map;
8+
static boolean[][] external;
9+
static int[] dy = { -1, 0, 1, 0 };
10+
static int[] dx = { 0, 1, 0, -1 };
11+
12+
public static void main(String[] args) throws IOException {
13+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
14+
StringTokenizer st = new StringTokenizer(br.readLine());
15+
N = Integer.parseInt(st.nextToken());
16+
M = Integer.parseInt(st.nextToken());
17+
18+
map = new int[N][M];
19+
int cheeseCount = 0;
20+
for (int i = 0; i < N; i++) {
21+
st = new StringTokenizer(br.readLine());
22+
for (int j = 0; j < M; j++) {
23+
map[i][j] = Integer.parseInt(st.nextToken());
24+
if (map[i][j] == 1) cheeseCount++;
25+
}
26+
}
27+
28+
int time = 0;
29+
while (cheeseCount > 0) {
30+
external = new boolean[N][M];
31+
markExternalAir();
32+
33+
List<int[]> meltList = new ArrayList<>();
34+
for (int i = 0; i < N; i++) {
35+
for (int j = 0; j < M; j++) {
36+
if (map[i][j] == 1) {
37+
int contact = 0;
38+
for (int d = 0; d < 4; d++) {
39+
int ny = i + dy[d];
40+
int nx = j + dx[d];
41+
if (ny < 0 || nx < 0 || ny >= N || nx >= M) continue;
42+
if (external[ny][nx] && map[ny][nx] == 0) {
43+
contact++;
44+
}
45+
}
46+
if (contact >= 2) {
47+
meltList.add(new int[]{i, j});
48+
}
49+
}
50+
}
51+
}
52+
for (int[] pos : meltList) {
53+
int y = pos[0], x = pos[1];
54+
map[y][x] = 0;
55+
cheeseCount--;
56+
}
57+
58+
time++;
59+
}
60+
61+
System.out.println(time);
62+
}
63+
64+
static void markExternalAir() {
65+
Queue<int[]> q = new LinkedList<>();
66+
boolean[][] visited = new boolean[N][M];
67+
q.offer(new int[]{0, 0});
68+
visited[0][0] = true;
69+
external[0][0] = true;
70+
71+
while (!q.isEmpty()) {
72+
int[] cur = q.poll();
73+
int y = cur[0], x = cur[1];
74+
for (int d = 0; d < 4; d++) {
75+
int ny = y + dy[d];
76+
int nx = x + dx[d];
77+
if (ny < 0 || nx < 0 || ny >= N || nx >= M) continue;
78+
if (visited[ny][nx]) continue;
79+
if (map[ny][nx] == 1) {
80+
continue;
81+
}
82+
visited[ny][nx] = true;
83+
external[ny][nx] = true;
84+
q.offer(new int[]{ny, nx});
85+
}
86+
}
87+
}
88+
}
89+
```

0 commit comments

Comments
 (0)