Skip to content

Commit 9a2b5a3

Browse files
authored
Merge pull request #650 from AlgorithmWithGod/JHLEE325
[20250812] BOJ / G4 / 인구 이동 / 이준희
2 parents b683f65 + f43c024 commit 9a2b5a3

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
static int n, l, r;
8+
static int[][] map;
9+
static boolean[][] visited;
10+
static int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
11+
12+
static List<int[]> union;
13+
static int unionSum;
14+
15+
public static void main(String[] args) throws Exception {
16+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
17+
StringTokenizer st = new StringTokenizer(br.readLine());
18+
19+
n = Integer.parseInt(st.nextToken());
20+
l = Integer.parseInt(st.nextToken());
21+
r = Integer.parseInt(st.nextToken());
22+
23+
map = new int[n][n];
24+
25+
for (int i = 0; i < n; i++) {
26+
st = new StringTokenizer(br.readLine());
27+
for (int j = 0; j < n; j++) {
28+
map[i][j] = Integer.parseInt(st.nextToken());
29+
}
30+
}
31+
32+
int days = 0;
33+
while (true) {
34+
visited = new boolean[n][n];
35+
boolean moved = false;
36+
37+
for (int i = 0; i < n; i++) {
38+
for (int j = 0; j < n; j++) {
39+
if (visited[i][j]) continue;
40+
41+
union = new ArrayList<>();
42+
unionSum = 0;
43+
bfs(new int[]{i, j});
44+
45+
if (union.size() > 1) {
46+
moved = true;
47+
int avg = unionSum / union.size();
48+
for (int[] cell : union) {
49+
map[cell[0]][cell[1]] = avg;
50+
}
51+
}
52+
}
53+
}
54+
55+
if (!moved) break;
56+
days++;
57+
}
58+
59+
System.out.println(days);
60+
}
61+
62+
static void bfs(int[] start){
63+
ArrayDeque<int[]> q = new ArrayDeque<>();
64+
int sr = start[0], sc = start[1];
65+
66+
visited[sr][sc] = true;
67+
q.add(new int[]{sr, sc});
68+
union.add(new int[]{sr, sc});
69+
unionSum += map[sr][sc];
70+
71+
while (!q.isEmpty()) {
72+
int[] cur = q.poll();
73+
int cr = cur[0], cc = cur[1];
74+
75+
for (int d = 0; d < 4; d++) {
76+
int nr = cr + dir[d][0];
77+
int nc = cc + dir[d][1];
78+
if (nr < 0 || nr >= n || nc < 0 || nc >= n) continue;
79+
if (visited[nr][nc]) continue;
80+
81+
int diff = Math.abs(map[cr][cc] - map[nr][nc]);
82+
if (diff >= l && diff <= r) {
83+
visited[nr][nc] = true;
84+
q.add(new int[]{nr, nc});
85+
union.add(new int[]{nr, nc});
86+
unionSum += map[nr][nc];
87+
}
88+
}
89+
}
90+
}
91+
}
92+
93+
```

0 commit comments

Comments
 (0)