티스토리 뷰
16234번: 인구 이동
N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모
www.acmicpc.net
풀이
from collections import deque
# 주어진 나라들에서 연합 찾기
def find_union(board, n, l, r):
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
groups = []
visited = [[False for _ in range(n)] for _ in range(n)]
# 모든 나라 순회, 연합 찾기
for x in range(n):
for y in range(n):
if visited[x][y]:
continue
# (열위치, 행위치)
new_group = [(x, y)]
q = deque()
q.append((x, y))
visited[x][y] = True
while q:
cx, cy = q.popleft()
for i in range(4):
nx = cx + dx[i]
ny = cy + dy[i]
if not (0 <= nx < n and 0 <= ny < n):
continue
if visited[nx][ny]:
continue
if not l <= abs(board[cx][cy] - board[nx][ny]) <= r:
continue
visited[nx][ny] = True
q.append((nx, ny))
new_group.append((nx, ny))
groups.append(new_group)
return groups
# 찾은 연합들의 인구 분배
def set_population(board, groups):
# 연합 순회, 각 연합 인구 분배
for group in groups:
population_of_group = [board[a][b] for a, b in group]
population_of_united = sum(population_of_group) // len(population_of_group)
for x, y in group:
board[x][y] = population_of_united
# 입력 받고, 인구 이동 시뮬레이션하여 결과 출력
def solution():
n, l, r = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(n)]
day = 0
while True:
# 연합을 찾아서, 연합이 더이상 생기지 않을 때까지 인구 분배 과정 반복
groups = find_union(board, n, l, r)
if not any(map(lambda x: len(x) > 1, groups)):
break
day += 1 # 인구 이동 횟수 누적
set_population(board, groups)
print(day)
if __name__ == "__main__":
solution()
'개발자를 위한 한 걸음 > 코딩 문제' 카테고리의 다른 글
톱니바퀴 - 백준 #14891, 골드5, 구현/시뮬레이션 (0) | 2023.04.14 |
---|---|
괄호 변환 - 프로그래머스 lv.2 (0) | 2023.04.14 |
연속합 - 백준 #1912, 실버2, 다이나믹 프로그래밍 (0) | 2023.04.09 |
Kth Smallest Element in a BST - LeetCode #230 (0) | 2023.04.06 |
Palindromic Substrings - LeetCode #647 (0) | 2023.04.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Python
- 릿코드
- 리트코드
- 정렬
- 너비 우선 탐색
- 백준
- 골드5
- 그래프 이론
- 깊이 우선 탐색
- 시뮬레이션
- leetcode
- 구현
- 카카오
- 브루트포스 알고리즘
- 카카오 코딩테스트
- lv.3
- Simulation
- 수학
- lv.2
- 프로그래머스
- 코딩테스트
- 그래프 탐색
- 백트래킹
- 코드트리
- 그리디 알고리즘
- 코딩 테스트
- 실버3
- 문자열
- 다이나믹 프로그래밍
- 실버2
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함