forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path7.java
113 lines (100 loc) Β· 3.81 KB
/
7.java
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.util.*;
class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
public class Main {
// λ
μ ν¬κΈ°(N), L, R κ°μ μ
λ ₯λ°κΈ°
public static int n, l, r;
public static int totalCount = 0;
// μ 체 λλΌμ μ 보(N x N)λ₯Ό μ
λ ₯λ°κΈ°
public static int[][] graph = new int[50][50];
public static int[][] unions = new int[50][50];
public static int[] dx = {-1, 0, 1, 0};
public static int[] dy = {0, -1, 0, 1};
// νΉμ μμΉμμ μΆλ°νμ¬ λͺ¨λ μ°ν©μ 체ν¬ν λ€μ λ°μ΄ν° κ°±μ
public static void process(int x, int y, int index) {
// (x, y)μ μμΉμ μ°κ²°λ λλΌ(μ°ν©) μ 보λ₯Ό λ΄λ 리μ€νΈ
ArrayList<Position> united = new ArrayList<>();
united.add(new Position(x, y));
// λλΉ μ°μ νμ (BFS)μ μν ν λΌμ΄λΈλ¬λ¦¬ μ¬μ©
Queue<Position> q = new LinkedList<>();
q.offer(new Position(x, y));
unions[x][y] = index; // νμ¬ μ°ν©μ λ²νΈ ν λΉ
int summary = graph[x][y]; // νμ¬ μ°ν©μ μ 체 μΈκ΅¬ μ
int count = 1; // νμ¬ μ°ν©μ κ΅κ° μ
// νκ° λΉ λκΉμ§ λ°λ³΅(BFS)
while (!q.isEmpty()) {
Position pos = q.poll();
x = pos.getX();
y = pos.getY();
// νμ¬ μμΉμμ 4κ°μ§ λ°©ν₯μ νμΈνλ©°
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// λ°λ‘ μμ μλ λλΌλ₯Ό νμΈνμ¬
if (0 <= nx && nx < n && 0 <= ny && ny < n && unions[nx][ny] == -1) {
// μμ μλ λλΌμ μΈκ΅¬ μ°¨μ΄κ° Lλͺ
μ΄μ, Rλͺ
μ΄νλΌλ©΄
int gap = Math.abs(graph[nx][ny] - graph[x][y]);
if (l <= gap && gap <= r) {
q.offer(new Position(nx, ny));
// μ°ν©μ μΆκ°νκΈ°
unions[nx][ny] = index;
summary += graph[nx][ny];
count += 1;
united.add(new Position(nx, ny));
}
}
}
}
// μ°ν© κ΅κ°λΌλ¦¬ μΈκ΅¬λ₯Ό λΆλ°°
for (int i = 0; i < united.size(); i++) {
x = united.get(i).getX();
y = united.get(i).getY();
graph[x][y] = summary / count;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
l = sc.nextInt();
r = sc.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
graph[i][j] = sc.nextInt();
}
}
// λ μ΄μ μΈκ΅¬ μ΄λμ ν μ μμ λκΉμ§ λ°λ³΅
while (true) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
unions[i][j] = -1;
}
}
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (unions[i][j] == -1) { // ν΄λΉ λλΌκ° μμ§ μ²λ¦¬λμ§ μμλ€λ©΄
process(i, j, index);
index += 1;
}
}
}
// λͺ¨λ μΈκ΅¬ μ΄λμ΄ λλ κ²½μ°
if (index == n * n) break;
totalCount += 1;
}
// μΈκ΅¬ μ΄λ νμ μΆλ ₯
System.out.println(totalCount);
}
}