N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모든 나라는 1×1 크기이기 때문에, 모든 국경선은 정사각형 형태이다.
오늘부터 인구 이동이 시작되는 날이다.
인구 이동은 하루 동안 다음과 같이 진행되고, 더 이상 아래 방법에 의해 인구 이동이 없을 때까지 지속된다.
- 국경선을 공유하는 두 나라의 인구 차이가 L명 이상, R명 이하라면, 두 나라가 공유하는 국경선을 오늘 하루 동안 연다.
- 위의 조건에 의해 열어야하는 국경선이 모두 열렸다면, 인구 이동을 시작한다.
- 국경선이 열려있어 인접한 칸만을 이용해 이동할 수 있으면, 그 나라를 오늘 하루 동안은 연합이라고 한다.
- 연합을 이루고 있는 각 칸의 인구수는 (연합의 인구수) / (연합을 이루고 있는 칸의 개수)가 된다. 편의상 소수점은 버린다.
- 연합을 해체하고, 모든 국경선을 닫는다.
각 나라의 인구수가 주어졌을 때, 인구 이동이 며칠 동안 발생하는지 구하는 프로그램을 작성하시오.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
//N, L, R 입력 받기
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
//그래프 초기화
int[][] graph = new int[n][n];
for(int i=0; i<n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < n; j++)
graph[i][j] = Integer.parseInt(st.nextToken());
}
//0일부터 시작해서 move()가 발생하지 않으면 끝
int day=0;
while(move(graph, l, r))
day++;
System.out.println(day);
}
//인구 이동시키고 이동 발생 여부를 리턴하는 메서드
public static boolean move(int[][] graph, int l, int r){
boolean isMoved=false;
int[][] directions=new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
boolean[][] visited = new boolean[graph.length][graph.length];
for(int i=0; i<graph.length; i++){
for(int j=0; j<graph.length; j++){
if(visited[i][j])
continue;
visited[i][j]=true;
List<int[]> countries = new ArrayList<>();
Queue<int[]> q=new LinkedList<>();
q.add(new int[]{i, j});
while(!q.isEmpty()){
int[] ptr = q.poll();
countries.add(ptr);
//모든 방향에 대해서 인구 차이가 L~R이면 방문하면서 countries 리스트에 추가
for(int[] d:directions){
int dx=ptr[0]+d[0];
int dy=ptr[1]+d[1];
if(dx<0 || dy<0 || dx>=graph.length || dy>=graph.length || visited[dx][dy])
continue;
int difference = Math.abs(graph[dx][dy] - graph[ptr[0]][ptr[1]]);
if(difference<l || r<difference)
continue;
visited[dx][dy]=true;
q.add(new int[]{dx, dy});
}
}
//연합이 혼자면 continue
if(countries.size()==1)
continue;
//연합이 혼자가 아니라면 이동
isMoved=true;
int result=calculate(graph, countries);
countries.forEach(o->graph[o[0]][o[1]]=result);
}
}
return isMoved;
}
//전체 인구수/전체 나라 수 계산 메서드
public static int calculate(int[][] graph, List<int[]> countries){
return countries.stream()
.mapToInt(o->graph[o[0]][o[1]])
.sum()/countries.size();
}
}
BFS를 사용해서 연합들을 모두 찾아준 뒤 해당 연합의 인구수를 갱신하다가 갱신이 더이상 일어나지 않으면 리턴!
😁