본문으로 바로가기

[BaekJoon] 백준 - 연구소 3

category 알고리즘/백준 2022. 7. 1. 10:39

문제

인체에 치명적인 바이러스를 연구하던 연구소에 승원이가 침입했고, 바이러스를 유출하려고 한다. 바이러스는 활성 상태와 비활성 상태가 있다. 가장 처음에 모든 바이러스는 비활성 상태이고, 활성 상태인 바이러스는 상하좌우로 인접한 모든 빈 칸으로 동시에 복제되며, 1초가 걸린다. 승원이는 연구소의 바이러스 M개를 활성 상태로 변경하려고 한다.

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

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

2 0 0 0 1 1 0
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 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 *

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

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
* - 3 2 3 4 *

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

입력

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

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

출력

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

 

 

 

풀이:

바이러스를 놓을 수 있는 장소에 한해서 M 개를 선택한 조합을 구한 후에

바이러스가 퍼지는 시간을 구하는 문제.

 

 

 

바이러스 조합 구하기 

dfs로 바이러스를 놓을 수 있는 장소 (virus) 를 탐색하면서 selectedVirus에 선택된 바이러스를 넣는다. 

M 개의 바이러스를 선택했다면 확산시키는 함수를 동작시킨다. 

 

 

 

 

 

 

전체 코드 >>

확산 시 주의할 점은 비활성 바이러스가 있는 자리는 시간에 측정되지 않는다는 것이다 (마지막 예제 참고)

BFS로 확산을 하되, 0을 감염시킨 경우에만 time을 depth + 1 만큼 갱신한다. 

 

연구소에 빈 칸이 없는 경우를 체크한 후에 모든 공간이 전파되었다면 최소값을 갱신한다. 

 

package com.company;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int N;
    static int M;
    static int A[][];
    static int MIN = 99999;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
        String[] tmp = br.readLine().split(" ");
        N = Integer.parseInt(tmp[0]);
        M = Integer.parseInt(tmp[1]);
        
        A = new int[N][N];
        List<int[]> virus = new ArrayList<>();
        
        for(int i = 0; i<N; i++) {
            String[] input = br.readLine().split(" ");
            for(int j = 0; j<N; j++) {
                A[i][j] = Integer.parseInt(input[j]);
                
                if (A[i][j] == 2) {
                    virus.add(new int[]{i, j}); // y x
                }
            }
        }
        
        dfs(virus, 0, 0, new ArrayList<>());
        if (MIN == 99999) {
            MIN = -1;
        }
        System.out.println(MIN);
    }
    
    private static void dfs(List<int[]> virus, int index, int count, List<int[]> selectedVirus) {
        if (count == M) {
            spread(selectedVirus);
            return;
        }
        
        if (index >= virus.size()) {
            return;
        }
        
        int[] v = virus.get(index);
        
        selectedVirus.add(new int[]{v[0], v[1]});
        dfs(virus, index+1, count+1, selectedVirus);
    
        
        selectedVirus.remove(selectedVirus.size() - 1);
        dfs(virus, index+1, count, selectedVirus);
    }
    
    private static void spread(List<int[]> list) {
        List<int[]> queue = new ArrayList<>();
        
        int[] dx = {1, -1, 0, 0};
        int[] dy = {0, 0, 1, -1};
        int[][] array = copyArray(A);
        boolean[][] visited = new boolean[N][N];
        
        for(int[] a : list) {
            queue.add(new int[]{a[0], a[1], 0});
            visited[a[0]][a[1]] = true;
            
        }
        
        int time = 0;
        
        while(!queue.isEmpty()) {
            int[] q = queue.remove(0);
            int x = q[1];
            int y = q[0];
            int depth = q[2];
            
            for(int i = 0; i<4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                
                if (nx < N && nx >= 0 && ny < N && ny >= 0 && !visited[ny][nx] && array[ny][nx] != -1) {
                    if (array[ny][nx] == 2) { // 비활성 바이러스가 있는 곳은 확산 시간에 책정되지 않는다. 
                        visited[ny][nx] = true;
                        queue.add(new int[]{ny, nx, depth+1});
                    }
                    if (array[ny][nx] == 0) {
                        visited[ny][nx] = true;
                        array[ny][nx] = 2;
                        time = depth+1;
                        queue.add(new int[]{ny, nx, depth+1});
                    }
                }
            }
        }
        
        boolean check = false;
        for(int i = 0; i<N; i++) {
            for(int j = 0; j<N; j++) {
                if (array[i][j] == 0) {
                    check = true; break;
                }
            }
        }
        
        if (!check) {
            MIN = Math.min(time, MIN);
        }
    }
    
    private static int[][] copyArray(int[][] target) {
        int[][] result = new int[N][N];
        
        for(int i = 0; i<N; i++) {
            for(int j = 0; j<N; j++) {
                result[i][j] = target[i][j];
            }
        }
        
        return result;
    }
}