Python Algorithms - DFS/BFS - "Population Migration"

Sunmi Shin·2022년 11월 20일

Python Algorithms

목록 보기
7/7
post-thumbnail

Problem:
How many times population migration occur in given conditions?
인구이동이 다음과 같은 조건일 때 얼마나 많이 일어나는가?

Conditions:

  1. They open the border when two countries share the border and the difference of population is greater and equal than L, and is less and equal than R.
  2. In population migration, the population in each country is (the total population / the number of countries ). Don't round up.
  3. Afterward, the border is closed.

Solutions:

from collections import deque

#Get input n(size of land), l and r.
n, l, r = map(int, input().split())

#Get information of population (n X n).
population = []
for _ in range(n):
	population.append(list(map(int, input().split())))

#Define directions, left and right, and up and down.
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]

result = 0 

def process(x, y, index):
	
    #Create a list containing (x, y) coordinate and border information.
    united = []
    united.append((x, y))
    
    #Define queue data structure for BFS.
    q= deque()
    q.append((x, y))
    union[x][y] = index  #The index(number) of current union.
    summary = population[x][y]  #The total population of current union. 
    coutnt = 1  #The number of countries of union.
    
    while q:
    	x, y = q.popleft()
        
        for i in range(4):
        	nx = x + dx[i]
            ny = y + dy[i]
            
            #Check if the countries share the borders and check if the union are not processed yet. 
            if 0 <= nx and nx < n and 0 <= ny and ny < n and union[nx][ny] == -1:
            #Define the difference of population. 
            difference = abs(population[nx][ny] - population[x][y])
            	if l <= difference <= r:
                  q.append((nx, ny))
                  #Add in union.
                  union[nx][ny] = index
                  summary += population[nx][ny]
                  count += 1
                  united.append((nx, ny))
	#Distribute population. 
    for i, j in united:
    	population[i][j] = summary // count
    return count
    
total count = 0

#Repeate a loop until population migration do not occur.
while True:
	union = [[-1] * n for _ in range(n)]
    index = 0
    for i in range(n):
    	for j in range(n):
        	if union[i][j] == -1:  #If the country is not processed. 
            	process(i, j, index)
                index += 1
                
    if index == n * n:  #After the migration ends. 
     	break
   	total_count += 1

#Print the total count of the migration. 
print(total_count)
profile
Tempest Data Analyst

0개의 댓글