알고리즘
[Java] 백준 16234번 인구 이동
J3SUNG
2023. 2. 10. 20:34
728x90
조건에 맞을때 인구이동이 일어납니다.
이 때 총 며칠동안 인구이동이 진행되는지 구하는 문제입니다.
N*N의 나라가 주어지며, 두 나라의 인구차가 L보다 크면서 R보다 작은 경우 인구이동이 발생합니다.
DFS방식으로 인구이동이 가능한 나라들을 찾아서 Queue에 담고 인구이동을 시켜주었습니다.
같은 곳에 방문하는 경우를 막기위해서 visit배열로 방문처리를 해주었습니다.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int n;
static int l;
static int r;
static int[][] map;
static boolean[][] visit;
static boolean chk;
static Queue<Pair> q = new LinkedList<Pair>();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
l = Integer.parseInt(st.nextToken());
r = Integer.parseInt(st.nextToken());
map = new int[n][n];
for(int i=0; i<n; ++i) {
st = new StringTokenizer(br.readLine());
for(int j=0; j<n; ++j) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
int cnt = 0;
while(cnt <= 2000) {
chk = false;
visit = new boolean[n][n];
for(int i=0; i<n; ++i) {
for(int j=0; j<n; ++j) {
if(!visit[i][j]) {
int num = 0;
num = DFS(i, j);
int size = q.size();
while(!q.isEmpty()) {
Pair p = q.poll();
map[p.y][p.x] = num / size;
}
}
}
}
if(!chk) {
bw.write(cnt + "");
bw.close();
return;
}
++cnt;
}
bw.write("-1");
bw.close();
}
public static int DFS(int y, int x) {
visit[y][x] = true;
int num = map[y][x];
int[] dy = {0, 1, 0, -1};
int[] dx = {1, 0, -1, 0};
q.add(new Pair(y, x));
for(int i=0; i<4; ++i) {
int nextY = y+dy[i];
int nextX = x+dx[i];
if(nextY < 0 || nextX < 0 || nextY >= n || nextX >= n || visit[nextY][nextX]) {
continue;
}
if(Math.abs(map[y][x] - map[nextY][nextX]) >= l && Math.abs(map[y][x] - map[nextY][nextX]) <= r) {
num += DFS(nextY, nextX);
chk = true;
}
}
return num;
}
static class Pair{
int y;
int x;
public Pair(int y, int x){
this.y = y;
this.x = x;
}
}
}