boj17141 - 연구소2 (Java)

이상욱·2022년 11월 24일
0

알고리즘

목록 보기
1/18


https://www.acmicpc.net/problem/17141

문제설명

인체에 치명적인 바이러스를 연구하던 연구소에 승원이가 침입했고, 바이러스를 유출하려고 한다. 승원이는 연구소의 특정 위치에 바이러스 M개를 놓을 것이고, 승원이의 신호와 동시에 바이러스는 퍼지게 된다.

연구소는 크기가 N×N인 정사각형으로 나타낼 수 있으며, 정사각형은 1×1 크기의 정사각형으로 나누어져 있다. 연구소는 빈 칸, 벽으로 이루어져 있으며, 벽은 칸 하나를 가득 차지한다.

일부 빈 칸은 바이러스를 놓을 수 있는 칸이다. 바이러스는 상하좌우로 인접한 모든 빈 칸으로 동시에 복제되며, 1초가 걸린다.

예를 들어, 아래와 같이 연구소가 생긴 경우를 살펴보자. 0은 빈 칸, 1은 벽, 2는 바이러스를 놓을 수 있는 칸이다.

0 0 1 0 1 2 0
0 1 1 0 1 0 0
0 1 0 0 0 0 0
0 0 0 2 0 1 1
0 1 0 0 0 0 0
2 1 0 0 0 0 2

M = 3이고, 바이러스를 아래와 같이 놓은 경우 6초면 모든 칸에 바이러스를 퍼뜨릴 수 있다. 벽은 -, 바이러스를 놓은 위치는 0, 빈 칸은 바이러스가 퍼지는 시간으로 표시했다.

6 6 5 4 - - 2
5 6 - 3 - 0 1
4 - - 2 - 1 2
3 - 2 1 2 2 3
2 2 1 0 1 - -
1 - 2 1 2 3 4
0 - 3 2 3 4 5

시간이 최소가 되는 방법은 아래와 같고, 5초만에 모든 칸에 바이러스를 퍼뜨릴 수 있다.

0 1 2 3 - - 2
1 2 - 3 - 0 1
2 - - 2 - 1 2
3 - 2 1 2 2 3
3 2 1 0 1 - -
4 - 2 1 2 3 4
5 - 3 2 3 4 5

연구소의 상태가 주어졌을 때, 모든 빈 칸에 바이러스를 퍼뜨리는 최소 시간을 구해보자.

입력
첫째 줄에 연구소의 크기 N(5 ≤ N ≤ 50), 놓을 수 있는 바이러스의 개수 M(1 ≤ M ≤ 10)이 주어진다.

둘째 줄부터 N개의 줄에 연구소의 상태가 주어진다. 0은 빈 칸, 1은 벽, 2는 바이러스를 놓을 수 있는 칸이다. 2의 개수는 M보다 크거나 같고, 10보다 작거나 같은 자연수이다.

출력
연구소의 모든 빈 칸에 바이러스가 있게 되는 최소 시간을 출력한다. 바이러스를 어떻게 놓아도 모든 빈 칸에 바이러스를 퍼뜨릴 수 없는 경우에는 -1을 출력한다.

풀이과정

  1. 바이러스들을 리스트에 저장한다.
  2. 바이러스들 중 m개를 뽑는 조합을 구한다.
  3. 기존 맵을 복사한 copyMap을 만들고 바이러스들을 0으로 만들어준다.
  4. 맵을 복사할 때 벽의 갯수가 맵의 바이러스들을 제외한 구역의 갯수와 같으면 min에 0을 저장한다.
  5. BFS를 통해 바이러스를 퍼트린다.
  6. copyMap을 check 하여 모두 퍼트릴 수 있는 최소거리를 구한다.
  7. 모든 조합을 마칠때마다 min값을 갱신해준다
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 Main {
	
	static int n,m;
	static int[][] map;
	static int[][] copyMap;
	static boolean[][] visit;
	static ArrayList<Point> emptyList = new ArrayList<>();
	static Point[] virusArr;
	static int min = Integer.MAX_VALUE;
	static int[] dx = {1,0,-1,0};
	static int[] dy = {0,1,0,-1};
	static boolean flag = false;
	public static void main(String[] args) throws Exception{
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		n = Integer.parseInt(st.nextToken());
		m = Integer.parseInt(st.nextToken());
		
		map = new int[n][n];
		
		virusArr = new Point[m];
		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());
				if(map[i][j] == 2) {
					emptyList.add(new Point(i,j));
				}
			}
		}
		
		comb(0,0);
		if(min == Integer.MAX_VALUE) {
			System.out.println(-1);
		}else {
			System.out.println(min);
		}
		
		

	}
	private static void comb(int cur, int start) {
		
		if(cur == m) {
			copyMap();
			spreadVirus();
			check();
			
			return;
		}
		
		for(int i = start; i < emptyList.size(); i++) {
			virusArr[cur] = emptyList.get(i); 
			comb(cur+1,i+1);
		}
		
	}

	private static void check() {
		
	
			for(int i = 0; i < n; i++) {
				for(int j = 0; j < n; j++) {
					if(copyMap[i][j] != 1 && !visit[i][j] ) {
						return;
						
					}
				}
			}

		int max = -1;
	
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				
				if(copyMap[i][j] > max) {
					max = copyMap[i][j];
				}
			}
		}
		
		if(min > max) {
			min = max;
		}
		

		
	}
	private static void copyMap() {
		copyMap = new int[n][n];
		
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				if(map[i][j] == 2) {
					copyMap[i][j] = 0;
				}else {
					copyMap[i][j]= map[i][j];
				}
				
			}
		}
        
        int cnt = 0;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                if(copyMap[i][j] == 1){
                    cnt++;
                }
            }
        }

        if(cnt == n*n-m){
            min = 0;
        }
		
	}
	

	private static void spreadVirus() {

		Queue<Point> q = new LinkedList<>();
		visit = new boolean[n][n];
		for(int i  = 0; i < virusArr.length; i++) {
			
			visit[virusArr[i].x][virusArr[i].y] = true;
			q.offer(virusArr[i]);
			
		}
		
		while(!q.isEmpty()) {
			
			Point p = q.poll();
			int x = p.x;
			int y = p.y;
			
			
			for(int i = 0; i < 4; i++) {
				int nx = x + dx[i];
				int ny = y + dy[i];
				
				if(nx >= 0 && nx < n && ny >= 0 && ny < n) {
					if(map[nx][ny] != 1 && !visit[nx][ny]) {
						copyMap[nx][ny] = copyMap[x][y] + 1;
						visit[nx][ny] = true;
						q.offer(new Point(nx,ny));
					}
				}
			}
			
				
		}

		
		
	}
}

class Point {
	int x;
	int y;
	Point(int x, int y){
		this.x = x;
		this.y = y;
	}
}
profile
항상 배우고 성장하는 안드로이드 개발자

0개의 댓글