14502번: 연구소

Joo·2022년 11월 14일

백준

목록 보기
4/113

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

문제

인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다.

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

일부 칸은 바이러스가 존재하며, 이 바이러스는 상하좌우로 인접한 빈 칸으로 모두 퍼져나갈 수 있다. 새로 세울 수 있는 벽의 개수는 3개이며, 꼭 3개를 세워야 한다.

예를 들어, 아래와 같이 연구소가 생긴 경우를 살펴보자.

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

이때, 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 곳이다. 아무런 벽을 세우지 않는다면, 바이러스는 모든 빈 칸으로 퍼져나갈 수 있다.

2행 1열, 1행 2열, 4행 6열에 벽을 세운다면 지도의 모양은 아래와 같아지게 된다.

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

바이러스가 퍼진 뒤의 모습은 아래와 같아진다.

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

벽을 3개 세운 뒤, 바이러스가 퍼질 수 없는 곳을 안전 영역이라고 한다. 위의 지도에서 안전 영역의 크기는 27이다.

연구소의 지도가 주어졌을 때 얻을 수 있는 안전 영역 크기의 최댓값을 구하는 프로그램을 작성하시오.

입력

첫째 줄에 지도의 세로 크기 N과 가로 크기 M이 주어진다. (3 ≤ N, M ≤ 8)

둘째 줄부터 N개의 줄에 지도의 모양이 주어진다. 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 위치이다. 2의 개수는 2보다 크거나 같고, 10보다 작거나 같은 자연수이다.

빈 칸의 개수는 3개 이상이다.

출력

첫째 줄에 얻을 수 있는 안전 영역의 최대 크기를 출력한다.

예제 입력 1

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

|| countOfWall >= 3

예제 출력 1

27

예제 입력 2

4 6
0 0 0 0 0 0
1 0 0 0 0 2
1 1 1 0 0 2
0 0 0 0 0 2

예제 출력 2

9

예제 입력 3

8 8
2 0 0 0 0 0 0 2
2 0 0 0 0 0 0 2
2 0 0 0 0 0 0 2
2 0 0 0 0 0 0 2
2 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

예제 출력 3

3

풀이

package graph_search;

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

public class Main_14502 {

    private static int height;
    private static int width;
    private static int maxSafeArea = Integer.MIN_VALUE;
    private static int[][] map;
    private static int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    private static boolean[][] existVirus;
    private static ArrayList<Virus> viruses = new ArrayList<>();

    static class Virus {
        int x;
        int y;

        public Virus(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    private static void input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        height = Integer.parseInt(st.nextToken());
        width = Integer.parseInt(st.nextToken());

        map = new int[height][width];
        existVirus = new boolean[height][width];

        for (int i = 0; i < height; i++) {
            st = new StringTokenizer(br.readLine());

            for (int j = 0; j < width; j++) {
                map[i][j] = Integer.parseInt(st.nextToken());
                // 초기 map 입력 시 2를 입력하면 x,y 좌표로 바이러스 객체를 만들고 해당 좌표 방문 표시
                if (map[i][j] == 2) {
                    viruses.add(new Virus(i, j));
                    existVirus[i][j] = true;
                }
            }
        }
    }

    private static void process() {
        buildWall(0, 0);
    }

    private static void buildWall(int wallIndex, int previousX) {
        // 벽 3개를 다 배치한 경우
        if (wallIndex > 2) {
            int currentSafeArea;
            int[][] newMap = spreadVirus();

            currentSafeArea = checkSafeArea(newMap);

            if (maxSafeArea < currentSafeArea) {
                maxSafeArea = currentSafeArea;
            }
        } else {    // 2. 벽 3개를 다 배치하지 않은 경우
            /**
             * 벽은 순서없이 배치하므로 같은 위치에만 있으면 같은 케이스임
             * 앞에 배치한 벽보다 이전 row 에 벽을 배치할 필요가 없으므로 previousX 를 활용해 구현
             * 주의!! 앞의 배치한 벽보다 column 은 작을 수 있음
             * ex)
             * 0 0 0 1
             * 1 0 0 0
             */
            for (int x = previousX; x < height; x++) {
                for (int y = 0; y < width; y++) {
                    if (map[x][y] == 2 || map[x][y] == 1) {
                        continue;
                    }

                    map[x][y] = 1;

                    buildWall(wallIndex + 1, x);

                    map[x][y] = 0;
                }
            }
        }
    }

    // 바이러스를 퍼트리는 메소드
    private static int[][] spreadVirus() {
        Queue<Virus> queue = new LinkedList();
        int[][] newMap = new int[height][width];
        boolean[][] newExistVirus = new boolean[height][width];

        // 시작 바이러스들을 큐에 넣어줌
        for (int i = 0; i < viruses.size(); i++) {
            queue.add(viruses.get(i));
        }
        
        // 2차원 배열의 깊은 복사
        // clone 사용해도 깊은 복사 안 됨!
        // 
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                // 이 때 맵은 3개의 벽이 세워진 상태의 맵
                newMap[i][j] = map[i][j];
                newExistVirus[i][j] = existVirus[i][j];
            }
        }
        
        while (!queue.isEmpty()) {
            Virus virus = queue.poll();
            int x = virus.x;
            int y = virus.y;

            for (int i = 0; i < 4; i++) {
                int newX = x + direction[i][0];
                int newY = y + direction[i][1];

                if (newX < 0 || newY < 0 || newX > height - 1 || newY > width - 1) {
                    continue;
                }

                if (newExistVirus[newX][newY]) {
                    continue;
                }

                if (newMap[newX][newY] == 1) {
                    continue;
                }

                // 조건을 모두 통과한 좌표
                // 바이러스 배치
                newMap[newX][newY] = 2;
                // exist check
                newExistVirus[newX][newY] = true;
                // 큐에 넣음
                queue.add(new Virus(newX, newY));
            }
        }

        return newMap;
    }

    // 안전 영역을 카운팅하는 메소드
    public static int checkSafeArea(int[][] newMap) {
        int countSafeArea = 0;

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (newMap[i][j] == 0) {
                    countSafeArea++;
                }
            }
        }

        return countSafeArea;
    }

    private static void output() {
        System.out.println(maxSafeArea);
    }

    public static void main(String[] args) throws IOException {
        input();
        process();
        output();
    }
}
  1. 먼저 3개의 벽을 세움
  2. 그 상태에서 바이러스가 갈 수 있는 모든 공간 탐색
  3. 안전 영역 확인 후 정답 갱신

0개의 댓글