[백준 16234번] 인구 이동

박형진·2022년 10월 29일
0

https://www.acmicpc.net/board/search/all/problem/16234/3


1. 코드(PyPy3)

import sys
from collections import deque

ans = 0
n, l, r = map(int, sys.stdin.readline().rstrip().split())
board = [list(map(int, sys.stdin.readline().rstrip().split())) for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]


def bfs(x, y):
    q = deque([(x, y)])
    result = [(x, y)]
    while q:
        x, y = q.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny]:
                if l <= abs(board[x][y] - board[nx][ny]) <= r:
                    visited[nx][ny] = True
                    q.append((nx, ny))
                    result.append((nx, ny))
    return result

while True:
    flag = False
    visited = [[False] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if not visited[i][j]:
                visited[i][j] = True
                unions = bfs(i, j)
                if len(unions) > 1:  # 연합이 생겼다면
                    flag = True
                    new = (sum([board[x][y] for x, y in unions]) // len(unions))
                    for x, y in unions:
                        board[x][y] = new
    if not flag:
        break
    ans += 1
print(ans)

2. 후기

2중 for문으로 모든 좌표가 root인 연합을 가정하고 BFS를 사용한다.

2중 for문 없이 한 번의 탐색으로 연합 여러개를 도출하려 했는데 구현하기 어려워서 포기했다.

profile
안녕하세요!

0개의 댓글