Skip to content

Commit 9f8c64b

Browse files
authored
Update 7.py
1 parent 35ec3d5 commit 9f8c64b

File tree

1 file changed

+22
-17
lines changed

1 file changed

+22
-17
lines changed

13/7.py

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
from collections import deque
22

3+
# 땅의 크기(N), L, R 값을 입력 받기
34
n, l, r = map(int, input().split())
4-
data = []
55

6+
# 전체 나라의 정보(N x N)를 입력 받기
7+
graph = []
68
for _ in range(n):
7-
data.append(list(map(int, input().split())))
9+
graph.append(list(map(int, input().split())))
810

911
dx = [-1, 0, 1, 0]
1012
dy = [0, -1, 0, 1]
@@ -13,31 +15,35 @@
1315

1416
# 특정 위치에서 출발하여 모든 연합을 체크한 뒤에 데이터 갱신
1517
def process(x, y, index):
16-
routes = []
17-
routes.append((x, y))
18-
# DFS를 위한 큐 자료구조 정의
18+
# (x, y)의 위치와 연결된 나라(연합) 정보를 담는 리스트
19+
united = []
20+
united.append((x, y))
21+
# 너비 우선 탐색 (BFS)을 위한 큐 자료구조 정의
1922
q = deque()
2023
q.append((x, y))
21-
union[x][y] = index
22-
summary = data[x][y]
23-
count = 1
24+
union[x][y] = index # 현재 연합의 번호 할당
25+
summary = graph[x][y] # 현재 연합의 전체 인구 수
26+
count = 1 # 현재 연합의 국가 수
2427
# 큐가 빌 때까지 반복(BFS)
2528
while q:
2629
x, y = q.popleft()
30+
# 현재 위치에서 4가지 방향을 확인하며
2731
for i in range(4):
2832
nx = x + dx[i]
2933
ny = y + dy[i]
30-
# 바로 옆 나라와 국경선이 열린 경우
34+
# 바로 옆에 있는 나라를 확인하여
3135
if 0 <= nx < n and 0 <= ny < n and union[nx][ny] == -1:
32-
if l <= abs(data[nx][ny] - data[x][y]) <= r:
36+
# 옆에 있는 나라와 인구 차이가 L명 이상, R명 이하라면
37+
if l <= abs(graph[nx][ny] - graph[x][y]) <= r:
38+
q.append((nx, ny))
39+
# 연합에 추가하기
3340
union[nx][ny] = index
34-
summary += data[nx][ny]
41+
summary += graph[nx][ny]
3542
count += 1
36-
q.append((nx, ny))
37-
routes.append((nx, ny))
43+
united.append((nx, ny))
3844
# 연합 국가끼리 인구를 분배
39-
for i, j in routes:
40-
data[i][j] = summary // count
45+
for i, j in united:
46+
graph[i][j] = summary // count
4147
return count
4248

4349
total_count = 0
@@ -51,11 +57,10 @@ def process(x, y, index):
5157
if union[i][j] == -1: # 해당 나라가 아직 처리되지 않았다면
5258
process(i, j, index)
5359
index += 1
54-
5560
# 모든 인구 이동이 끝난 경우
5661
if index == n * n:
5762
break
58-
5963
total_count += 1
6064

65+
# 인구 이동 횟수 출력
6166
print(total_count)

0 commit comments

Comments
 (0)