https://www.acmicpc.net/problem/16234
"""
"""
from collections import deque
from sys import stdin
from copy import deepcopy
input = stdin.readline
N, L, R = map(int, input().split())
pan = [ list(map(int, input().split())) for _ in range(N) ]
dx, dy = [0, 0, -1, 1], [-1, 1, 0, 0]
answer = 0
def bfs(x, y):
visited[x][y] = True
q = deque([(x, y)])
# 국경선을 공유하는 좌표의 모음과 인구수
tmp = []
population = 0
while q:
px, py = q.popleft()
population += pan[px][py]
tmp.append((px, py))
for k in range(4):
mx = px + dx[k]
my = py + dy[k]
# 현재 나라와 인접한 나라와 인구수의 차이가 L 이상 R 이하라면 방문처리를 하고 좌표를 큐에 넣어준다.
if 0 <= mx < N and 0 <= my < N and not visited[mx][my]:
if L <= abs(pan[mx][my] - pan[px][py]) <= R:
visited[mx][my] = True
q.append((mx, my))
# 국경선을 공유하는 나라들은 인구수를 조정한다.
for a, b in tmp:
pan[a][b] = population // len(tmp)
while True:
visited = [[False] * N for _ in range(N)]
# 인구이동 시작 하기전에 배열을 임시 복사
tmp = deepcopy(pan)
# 인구이동 시작
for i in range(N):
for j in range(N):
if not visited[i][j]:
bfs(i, j)
# 인구이동 시작하기전과 후의 배열을 비교하여 인구이동이 일어나지 않으면 break
if tmp != pan:
answer += 1
else:
break
print(answer)
문제 설명 그대로 코드를 구현하면 쉽게 풀 수 있다.
자세한 내용은 주석에 달아 놓음.