문제 설명
N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모든 나라는 1×1 크기이기 때문에, 모든 국경선은 정사각형 형태이다.
오늘부터 인구 이동이 시작되는 날이다.
인구 이동은 하루 동안 다음과 같이 진행되고, 더 이상 아래 방법에 의해 인구 이동이 없을 때까지 지속된다.
각 나라의 인구수가 주어졌을 때, 인구 이동이 며칠 동안 발생하는지 구하는 프로그램을 작성하시오.
입력
첫째 줄에 N, L, R이 주어진다. (1 ≤ N ≤ 50, 1 ≤ L ≤ R ≤ 100)
둘째 줄부터 N개의 줄에 각 나라의 인구수가 주어진다. r행 c열에 주어지는 정수는 A[r][c]의 값이다. (0 ≤ A[r][c] ≤ 100)
인구 이동이 발생하는 일수가 2,000번 보다 작거나 같은 입력만 주어진다.
출력
인구 이동이 며칠 동안 발생하는지 첫째 줄에 출력한다.
간단한 BFS 시뮬레이션 문제입니다.
계획을 나눠보면 다음과 같습니다.
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception {
StringTokenizer stk = new StringTokenizer(br.readLine());
int N = Integer.parseInt(stk.nextToken());
int L = Integer.parseInt(stk.nextToken());
int R = Integer.parseInt(stk.nextToken());
Queue<int[]> q = new LinkedList<>();
Queue<int[]> nationCoords = new LinkedList<>();
int[] my = {-1, 0, 1, 0};
int[] mx = {0, 1, 0, -1};
boolean[][] open = new boolean[N][N];
int[][] land = new int[N][N];
for (int i = 0; i < N; i++) {
stk = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
land[i][j] = Integer.parseInt(stk.nextToken());
}
}
int ans = 0;
while (true) {
boolean isContinue = false;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (open[i][j]) continue;
// 1. 연합하지 않은 나라라면 인접한 연합할 수 있는 나라를 찾습니다.
int sumOfPopulation = land[i][j];
int [] coord = new int[] {i, j}; // 메모리 아끼기
q.add(coord);
nationCoords.add(coord);
open[i][j] = true;
while (!q.isEmpty()) {
int[] cur = q.poll();
int y = cur[0];
int x = cur[1];
for (int dir = 0; dir < 4; dir++) {
int ny = y + my[dir];
int nx = x + mx[dir];
// 범위를 벗어났을 때
if (ny < 0 || ny >= N || nx < 0 || nx >= N) continue;
// 이미 국경선을 오픈한 국가일 때
if (open[ny][nx]) continue;
// 국가간의 인구수 차이가 L이상 R이하라면
int populationDiff = Math.abs(land[y][x] - land[ny][nx]);
if (populationDiff >= L && populationDiff <= R) {
int[] newCoord = new int[] {ny, nx}; // 메모리 아끼기
q.add(newCoord);
nationCoords.add(newCoord);
open[ny][nx] = true;
sumOfPopulation += land[ny][nx];
isContinue = true; // 연합할 수 있는 나라가 있다면 계속 진행
}
}
}
// 2. 연합된 나라끼리 인구를 합쳐줍니다.
int avg = Math.round(sumOfPopulation / nationCoords.size());
while (!nationCoords.isEmpty()) {
int[] nationCoord = nationCoords.poll();
int y = nationCoord[0];
int x = nationCoord[1];
land[y][x] = avg;
}
}
}
// 3. 연합한 나라가 하나도 없다면 루프를 빠져나갑니다.
if (!isContinue) break;
// 연합 체크 초기화
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
open[i][j] = false;
}
}
ans++;
}
bw.write(ans + "");
bw.close();
}
}