출처 : https://www.acmicpc.net/problem/16234
16234번: 인구 이동
N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모든 나라는 1×1 크기이기 때문에, 모든 국경선은 정사각형 형태이다. 오늘부터 인구 이동이 시작되는 날이다. 인구 이동은 다음과 같이 진행되고, 더 이상 아래 방법에 의해 인구 이동이 없을 때까지 지속된다. 국경선을 공유하는 두 나라의 인구 차이가 L명
www.acmicpc.net
pypy3로는 통과했지만, 시간초과 문제로 python은 통과되지 못했다.
아직 시간초과문제에 많이 취약하다는 것이겠지..
# Code
from collections import deque
def bfs(x, y):
sumv = 0
visited = set()
q = deque()
q.append((x, y))
while q:
node = q.popleft()
if check[node[0]][node[1]] == 0: continue
visited.add((node[0], node[1]))
check[node[0]][node[1]] = 0
sumv = sumv + city[node[0]][node[1]]
for i in range(4):
nx, ny = node[0] + dx[i], node[1] + dy[i]
if not (0 <= nx < N and 0 <= ny < N): continue
if not (L <= abs(city[node[0]][node[1]] - city[nx][ny]) <= R): continue
if check[nx][ny] == 0: continue
q.append((nx, ny))
return visited, sumv // len(visited)
if __name__ == '__main__':
N, L, R = map(int, input().split())
city = [list(map(int, input().split())) for _ in range(N)]
cnt = 0
dx = (0, 1, 0, -1)
dy = (1, 0, -1, 0)
check = [[-1]*N for _ in range(N)]
while True:
flag = 0
for x in range(N):
for y in range(N):
if check[x][y] == 0: continue
array, change = bfs(x, y)
if len(array) > 1:
flag = 1
for i, j in array:
city[i][j] = change
if flag == 0: break
for i in range(N):
for j in range(N):
check[i][j] = -1
cnt = cnt + 1
print(cnt)
|
cs |
'알고리즘 > [Python] 백준' 카테고리의 다른 글
(Python) 백준 18808번: 스티커 붙이기 (0) | 2020.03.24 |
---|---|
(Python) 백준 16235번: 나무 재테크 (1) | 2020.03.20 |
(Python) 백준 5373번: 큐빙 (0) | 2020.03.11 |
(Python) 백준 17144번: 미세먼지 안녕! (0) | 2020.03.10 |
(Python) 백준 15686번: 치킨 배달 (0) | 2020.03.10 |