본문 바로가기
백준

[python] 16234. 인구 이동

by DylanMsK 2019. 7. 27.

문제 출처

16234. 인구 이동

 

풀이


N, L, R = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(N)]

def find_unions():
    brr = [[0]*N for _ in range(N)]
    unions = {}
    n = 1
    for i in range(N):
        for j in range(N):
            if brr[i][j] == 0:
                q = [(j, i, arr[i][j])]
                idx = 0
                brr[i][j] = 1
                while 1:
                    x, y, p = q[idx]
                    for dx, dy in (0, -1), (1, 0), (0, 1), (-1, 0):
                        nx, ny = x+dx, y+dy
                        if nx < 0 or nx >= N or ny < 0 or ny >= N:
                            continue
                        if brr[ny][nx] or abs(p - arr[ny][nx]) < L or abs(p - arr[ny][nx]) > R:
                            continue
                        brr[ny][nx] = 1
                        q.append((nx, ny, arr[ny][nx]))

                    if idx == len(q)-1:
                        break
                    idx += 1

                if idx:
                    unions[n] = q
                    n += 1
    if unions:
        return unions
    return None

cnt = 0
while 1:
    unions = find_unions()
    if unions:
        cnt += 1
        for n in unions:
            union = unions[n]
            sum_, length = sum([c[2] for c in union]), len(union)
            p = int(sum_ / length)
            for country in union:
                x, y, _ = country
                arr[y][x] = p
    else:
        break

print(cnt)

'백준' 카테고리의 다른 글

[python] 14500. 테트로미노  (0) 2019.08.04
[python] 17444. 미세먼지 안녕!  (0) 2019.08.04
[python] 17140. 이차원 배열과 연산  (0) 2019.07.24
[python] 3190. 뱀  (0) 2019.07.24
[python] 14891. 톱니바퀴  (0) 2019.07.24