Skip to content

Commit 9d3b310

Browse files
authored
Merge pull request #2021 from AlgorithmWithGod/JHLEE325
[20260314] BOJ / G4 / 연구소 2 / 이준희
2 parents a0238cb + 4195d87 commit 9d3b310

1 file changed

Lines changed: 92 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)