BOJ 16234

2021-02-28

위 문제는 백준 사이트의 알고리즘 16234 문제에 관한 설명입니다.


문제

N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다.

각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다.

인접한 나라 사이에는 국경선이 존재한다.

모든 나라는 1×1 크기이기 때문에, 모든 국경선은 정사각형 형태이다.

오늘부터 인구 이동이 시작되는 날이다.

인구 이동은 다음과 같이 진행되고, 더 이상 아래 방법에 의해 인구 이동이 없을 때까지 지속된다.

  • 국경선을 공유하는 두 나라의 인구 차이가 L명 이상, R명 이하라면, 두 나라가 공유하는 국경선을 오늘 하루동안 연다.
  • 위의 조건에 의해 열어야하는 국경선이 모두 열렸다면, 인구 이동을 시작한다.
  • 국경선이 열려있어 인접한 칸만을 이용해 이동할 수 있으면, 그 나라를 오늘 하루 동안은 연합이라고 한다.
  • 연합을 이루고 있는 각 칸의 인구수는 (연합의 인구수) / (연합을 이루고 있는 칸의 개수)가 된다. 편의상 소수점은 버린다.
  • 연합을 해체하고, 모든 국경선을 닫는다.

각 나라의 인구수가 주어졌을 때, 인구 이동이 몇 번 발생하는지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N, L, R이 주어진다. (1 ≤ N ≤ 50, 1 ≤ L ≤ R ≤ 100)

둘째 줄부터 N개의 줄에 각 나라의 인구수가 주어진다.

r행 c열에 주어지는 정수는 A[r][c]의 값이다. (0 ≤ A[r][c] ≤ 100)

인구 이동이 발생하는 횟수가 2,000번 보다 작거나 같은 입력만 주어진다.

출력

인구 이동이 몇 번 발생하는지 첫째 줄에 출력한다.

package 삼성기출;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class 인구이동 {
  static StringTokenizer st;
  static int[] dx = { 1, 0, -1, 0 };
  static int[] dy = { 0, 1, 0, -1 };
  static int N;
  static int L;
  static int R;
  static int answer;

  public static void main(String[] args) throws Exception {
  	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  	st = new StringTokenizer(br.readLine());
  	N = Integer.parseInt(st.nextToken());
  	L = Integer.parseInt(st.nextToken());
  	R = Integer.parseInt(st.nextToken());
 	int[][] map = new int[N + 1][N + 1];
	boolean[][] visited = new boolean[N + 1][N + 1];

	for (int i = 1; i <= N; i++) {
		st = new StringTokenizer(br.readLine());
		for (int j = 1; j <= N; j++) {
			map[i][j] = Integer.parseInt(st.nextToken());
		}
	}
	answer = 0;
	boolean possibleMoving = false;
	while (!possibleMoving) {
		Queue<Point> queue = new LinkedList<>();
		ArrayList<Point> list = new ArrayList<>(); 
		int sum = 0;
		int count = 0;
			for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				queue.add(new Point(i, j));
				while (!queue.isEmpty()) {
					Point temp = queue.poll();
					if (!visited[temp.x][temp.y]) {
						visited[temp.x][temp.y] = true;
						count++;
						sum += map[temp.x][temp.y];
						list.add(new Point(temp.x, temp.y));
						for (int dir = 0; dir < 4; dir++) {
							int nextX = temp.x + dx[dir];
							int nextY = temp.y + dy[dir];
							if (isIn(nextX, nextY) && !visited[nextX][nextY]
									&& isPossibleMove(map[temp.x][temp.y], map[nextX][nextY])) {
								queue.add(new Point(nextX, nextY));
							}
						}
					}
				}
					if (list.size() > 1) {
					int movingSum = sum / count;
					for (int k = 0; k < list.size(); k++) {
						Point temp = list.get(k);
						map[temp.x][temp.y] = movingSum;
					}
					possibleMoving = true;
				}
				list = new ArrayList<>();
				sum = 0;
				count = 0;
			}
		} 
		if (possibleMoving) {
			answer++;
			possibleMoving = false;
			visited = new boolean[N + 1][N + 1];
		} else
			break;
	}
	System.out.println(answer);
  }
  private static boolean isIn(int nextX, int nextY) {
	if(0 < nextX && nextX <= N && 0 < nextY && nextY <= N)
		return true;
	else 
		return false;
  }
  private static boolean isPossibleMove(int curCount, int nextCount) {
	int absCount = Math.abs(curCount - nextCount);
	if (absCount >= L && absCount <= R)
		return true;
	else
		return false;
  }
  private static class Point {
	int x;
	int y;
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
  }
}

이번 문제는 시뮬레이션 문제입니다.

부분을 나눠서 설명해보겠습니다.

입력부

  	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  	st = new StringTokenizer(br.readLine());
  	N = Integer.parseInt(st.nextToken());
  	L = Integer.parseInt(st.nextToken());
  	R = Integer.parseInt(st.nextToken());
 	int[][] map = new int[N + 1][N + 1];
	boolean[][] visited = new boolean[N + 1][N + 1];

	for (int i = 1; i <= N; i++) {
		st = new StringTokenizer(br.readLine());
		for (int j = 1; j <= N; j++) {
			map[i][j] = Integer.parseInt(st.nextToken());
		}
	}
	answer = 0;
	boolean possibleMoving = false;

각각의 입력값을 받아주고, possibleMoving은 인구이동이 가능한가 확인합니다.

BFS부

	while (!possibleMoving) {
		Queue<Point> queue = new LinkedList<>();
		ArrayList<Point> list = new ArrayList<>(); 
		int sum = 0;
		int count = 0;
			for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				queue.add(new Point(i, j));
				while (!queue.isEmpty()) {
					Point temp = queue.poll();
					if (!visited[temp.x][temp.y]) {
						visited[temp.x][temp.y] = true;
						count++;
						sum += map[temp.x][temp.y];
						list.add(new Point(temp.x, temp.y));
						for (int dir = 0; dir < 4; dir++) {
							int nextX = temp.x + dx[dir];
							int nextY = temp.y + dy[dir];
							if (isIn(nextX, nextY) && !visited[nextX][nextY]
									&& isPossibleMove(map[temp.x][temp.y], map[nextX][nextY])) {
								queue.add(new Point(nextX, nextY));
							}
						}
					}
				}
					if (list.size() > 1) {
					int movingSum = sum / count;
					for (int k = 0; k < list.size(); k++) {
						Point temp = list.get(k);
						map[temp.x][temp.y] = movingSum;
					}
					possibleMoving = true;
				}
				list = new ArrayList<>();
				sum = 0;
				count = 0;
			}
		} 
		if (possibleMoving) {
			answer++;
			possibleMoving = false;
			visited = new boolean[N + 1][N + 1];
		} else
			break;
	}

queue에는 BFS를 위한 생성,

list에는 이동한 점의 좌표 정보들,

sum에는 인구 이동할 나라의 사람 수,

count에는 인구 이동한 나라의 수 가 들어갑니다.

모든 지점에 대해서 BFS를 시작합니다.

일단 현재 있는 위치에 대해서 sum에다가 인구의 숫자를 더 해주고,

지금 위치에 대한 갯수와 좌표를 저장합니다.

그리고 그 주변의 4가지 방향으로 이동할 수 있는가 없는가를 확인하는게 필요합니다.

해당 부분을 빠져나오게 되면,

방문한 좌표에 대해서 이동이 필요한가를 판별하고,

새로 시작하기 떄문에 시작점에 대해 다시 조사하기 위해 초기화가 필요합니다.

부가적인 메소드들

  private static boolean isIn(int nextX, int nextY) {
	if(0 < nextX && nextX <= N && 0 < nextY && nextY <= N)
		return true;
	else 
		return false;
  }
  private static boolean isPossibleMove(int curCount, int nextCount) {
	int absCount = Math.abs(curCount - nextCount);
	if (absCount >= L && absCount <= R)
		return true;
	else
		return false;
  }
  private static class Point {
	int x;
	int y;
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
  }

isIn은 좌표가 map의 내부에 있는가 판단해줍니다.

isPossibleMove는 국경을 연결하기 위해서는 L이상 R이하의 조건이므로 그것을 판단해줍니다.

Point 클래스는 좌표지점에 대해서 정보를 가지고 있습니다.

인구이동