forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path7.py
63 lines (56 loc) Β· 2.09 KB
/
7.py
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
from collections import deque
# λ
μ ν¬κΈ°(N), L, R κ°μ μ
λ ₯λ°κΈ°
n, l, r = map(int, input().split())
# μ 체 λλΌμ μ 보(N x N)λ₯Ό μ
λ ₯ λ°κΈ°
graph = []
for _ in range(n):
graph.append(list(map(int, input().split())))
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
# νΉμ μμΉμμ μΆλ°νμ¬ λͺ¨λ μ°ν©μ 체ν¬ν λ€μ λ°μ΄ν° κ°±μ
def process(x, y, index):
# (x, y)μ μμΉμ μ°κ²°λ λλΌ(μ°ν©) μ 보λ₯Ό λ΄λ 리μ€νΈ
united = []
united.append((x, y))
# λλΉ μ°μ νμ (BFS)μ μν ν λΌμ΄λΈλ¬λ¦¬ μ¬μ©
q = deque()
q.append((x, y))
union[x][y] = index # νμ¬ μ°ν©μ λ²νΈ ν λΉ
summary = graph[x][y] # νμ¬ μ°ν©μ μ 체 μΈκ΅¬ μ
count = 1 # νμ¬ μ°ν©μ κ΅κ° μ
# νκ° λΉ λκΉμ§ λ°λ³΅(BFS)
while q:
x, y = q.popleft()
# νμ¬ μμΉμμ 4κ°μ§ λ°©ν₯μ νμΈνλ©°
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# λ°λ‘ μμ μλ λλΌλ₯Ό νμΈνμ¬
if 0 <= nx < n and 0 <= ny < n and union[nx][ny] == -1:
# μμ μλ λλΌμ μΈκ΅¬ μ°¨μ΄κ° Lλͺ
μ΄μ, Rλͺ
μ΄νλΌλ©΄
if l <= abs(graph[nx][ny] - graph[x][y]) <= r:
q.append((nx, ny))
# μ°ν©μ μΆκ°νκΈ°
union[nx][ny] = index
summary += graph[nx][ny]
count += 1
united.append((nx, ny))
# μ°ν© κ΅κ°λΌλ¦¬ μΈκ΅¬λ₯Ό λΆλ°°
for i, j in united:
graph[i][j] = summary // count
total_count = 0
# λ μ΄μ μΈκ΅¬ μ΄λμ ν μ μμ λκΉμ§ λ°λ³΅
while True:
union = [[-1] * n for _ in range(n)]
index = 0
for i in range(n):
for j in range(n):
if union[i][j] == -1: # ν΄λΉ λλΌκ° μμ§ μ²λ¦¬λμ§ μμλ€λ©΄
process(i, j, index)
index += 1
# λͺ¨λ μΈκ΅¬ μ΄λμ΄ λλ κ²½μ°
if index == n * n:
break
total_count += 1
# μΈκ΅¬ μ΄λ νμ μΆλ ₯
print(total_count)