Skip to content

Commit 1ab11f1

Browse files
committed
[BOJ] #16234. 인구이동 / 골드4 / 80분 / 실패
1 parent 63a7d33 commit 1ab11f1

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import sys
2+
from collections import deque
3+
input = sys.stdin.readline
4+
5+
def bfs(x, y):
6+
queue = deque([(x, y)])
7+
union = [(x, y)] # 연합에 포함된 나라들을 저장할 리스트
8+
visited[x][y] = 1 # 현재 나라를 방문 표시
9+
total_population = nation[x][y] # 연합의 총 인구 수
10+
11+
while queue:
12+
x, y = queue.popleft() # 큐에서 하나의 나라를 꺼냄
13+
for nx, ny in ((-1, 0), (1, 0), (0, -1), (0, 1)): # 인접한 네 방향 확인
14+
dx, dy = x + nx, y + ny
15+
# 범위 내에 있고, 아직 방문하지 않은 곳이라면
16+
if (0 <= dx < N and 0 <= dy < N) and visited[dx][dy] == 0:
17+
# 두 나라의 인구의 차이가 L이상 R이하라면(=연합이 된다면)
18+
if L <= abs(nation[dx][dy] - nation[x][y]) <= R:
19+
visited[dx][dy] = 1 # 방문 표시
20+
queue.append((dx, dy)) # 큐에 추가
21+
union.append((dx, dy)) # 연합에 추가
22+
total_population += nation[dx][dy] # 연합 인구 추가
23+
24+
# 연합이 2개 이상의 나라로 이루어졌을 경우
25+
if len(union) > 1:
26+
new_population = total_population // len(union) # 새로운 인구 수 계산
27+
for i, j in union:
28+
nation[i][j] = new_population # 연합 내의 모든 나라에 인구 재배치
29+
return True # 인구 이동이 일어났음
30+
31+
return False # 인구 이동이 일어나지 않음
32+
33+
N, L, R = map(int, input().split())
34+
nation = [list(map(int, input().split())) for _ in range(N)]
35+
day = 0 # 인구이동 발생 일수
36+
37+
while True:
38+
visited = [[0] * N for _ in range(N)]
39+
is_moved = False # 인구 이동이 발생했는지 여부를 저장할 변수
40+
41+
# 모든 나라를 탐색하며 연합 형성, 인구 이동 확인
42+
for i in range(N):
43+
for j in range(N):
44+
if not visited[i][j]: # 방문하지 않은 나라에서 BFS 시작
45+
visited[i][j] = 1 # 방문 표시
46+
if bfs(i, j): # 한 번이라도 인구 이동이 발생했다면
47+
is_moved = True # 인구 이동이 발생했음을 표시
48+
49+
if not is_moved: # 인구 이동이 발생하지 않았다면 종료
50+
break
51+
52+
day += 1 # 인구 이동이 발생한 날 수 증가
53+
54+
print(day)

0 commit comments

Comments
 (0)