Jae-Kyung Cho LLM Developers who was a Robotics engineer

Baekjoon-16234-인구 이동

from collections import deque
import sys
input = sys.stdin.readline
N,L,R = map(int,input().split())

land = [list(map(int,input().split())) for _ in range(N)]
dirs = [[0,1],[1,0],[0,-1],[-1,0]]

count = 0
while True:
    # BFS
    move_sets = []
    visited = [[0]*N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if visited[i][j]==0:
                q = deque([[i,j]])
                move_sets.append([[i,j]])
                visited[i][j] = 1
                while q:
                    r,c = q.popleft()
                    for dr,dc in dirs:
                        nr,nc = r+dr,c+dc
                        if 0<=nr<N and 0<=nc<N and visited[nr][nc]==0:
                            if L<=abs(land[r][c]-land[nr][nc])<=R:
                                visited[nr][nc] = 1
                                q.append([nr,nc])
                                move_sets[-1].append([nr,nc])
    
    if len(move_sets) == N**2:
        break
    else:
        for move_set in move_sets:
            total = 0
            for x,y in move_set:
                total += land[x][y]
            for x,y in move_set:
                land[x][y] = int(total/len(move_set))
        count += 1

print(count)
Comments