코테/코딩테스트 대비 Python

백준 인구이동 BFS

밤밭황제 2023. 5. 21. 23:04

https://www.acmicpc.net/problem/16234

 

16234번: 인구 이동

N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모

www.acmicpc.net

확산 문제 풀 때 -> 2차원 배열 돌면서 visit 처리 -> visit 안된거 있으면 bfs or dfs <탐색하면서 확산된것은 visit처리>

from collections import deque
N, L, R = map(int, input().split())
population = []

dx = [0, 0, 1, -1]
dy =[1, -1, 0, 0]
for i in range(0, N):
   population.append(list(map(int, input().split())))       
   
def bfs(x,y, visit):
    ret = False
    s = set()
    q = deque()
    q.append((x,y))
    visit[x][y] = 1
    total = 0
    cnt = 0
    while q:
        x, y = q.popleft()
        s.add((x,y)) 
        total += population[x][y]
        cnt += 1
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < N and 0 <= ny < N and visit[nx][ny] == 0: 
                if L <= abs(population[x][y] - population[nx][ny]) <= R:
                    visit[nx][ny] = 1
                    q.append((nx, ny))
    if len(s) > 1:
        ret = True 
    p = total // cnt
    while s:
        x,y = s.pop()
        population[x][y] = p
    return ret
    # print(visit)
answer = 0
again = True
while again:
    flag = False
    visit = [[0 for _ in range(N)] for _ in range(N)] 
    for i in range(0, N):
        for j in range(0, N):
            if visit[i][j] == 0:
                repeat = bfs(i,j, visit)
                if repeat == True:
                    flag = True
    again = flag
    if flag == True:
        answer += 1
print(answer)
728x90