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

문제

스타트링크의 사무실은 1×1크기의 정사각형으로 나누어져 있는 N×M 크기의 직사각형으로 나타낼 수 있다. 사무실에는 총 K개의 CCTV가 설치되어져 있는데, CCTV는 5가지 종류가 있다. 각 CCTV가 감시할 수 있는 방법은 다음과 같다.

1번 CCTV는 한 쪽 방향만 감시할 수 있다. 2번과 3번은 두 방향을 감시할 수 있는데, 2번은 감시하는 방향이 서로 반대방향이어야 하고, 3번은 직각 방향이어야 한다. 4번은 세 방향, 5번은 네 방향을 감시할 수 있다.

CCTV는 감시할 수 있는 방향에 있는 칸 전체를 감시할 수 있다. 사무실에는 벽이 있는데, CCTV는 벽을 통과할 수 없다. CCTV가 감시할 수 없는 영역은 사각지대라고 한다.

CCTV는 회전시킬 수 있는데, 회전은 항상 90도 방향으로 해야 하며, 감시하려고 하는 방향이 가로 또는 세로 방향이어야 한다.

0 0 0 0 0 0
0 0 0 0 0 0
0 0 1 0 6 0
0 0 0 0 0 0

지도에서 0은 빈 칸, 6은 벽, 1~5는 CCTV의 번호이다. 위의 예시에서 1번의 방향에 따라 감시할 수 있는 영역을 '#'로 나타내면 아래와 같다.

CCTV는 벽을 통과할 수 없기 때문에, 1번이 → 방향을 감시하고 있을 때는 6의 오른쪽에 있는 칸을 감시할 수 없다.

0 0 0 0 0 0
0 2 0 0 0 0
0 0 0 0 6 0
0 6 0 0 2 0
0 0 0 0 0 0
0 0 0 0 0 5

위의 예시에서 감시할 수 있는 방향을 알아보면 아래와 같다.

CCTV는 CCTV를 통과할 수 있다. 아래 예시를 보자.

0 0 2 0 3
0 6 0 0 0
0 0 6 6 0
0 0 0 0 0

위와 같은 경우에 2의 방향이 ↕ 3의 방향이 ←와 ↓인 경우 감시받는 영역은 다음과 같다.

# # 2 # 3
0 6 # 0 #
0 0 6 6 #
0 0 0 0 #

사무실의 크기와 상태, 그리고 CCTV의 정보가 주어졌을 때, CCTV의 방향을 적절히 정해서, 사각 지대의 최소 크기를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 사무실의 세로 크기 N과 가로 크기 M이 주어진다. (1 ≤ N, M ≤ 8)

둘째 줄부터 N개의 줄에는 사무실 각 칸의 정보가 주어진다. 0은 빈 칸, 6은 벽, 1~5는 CCTV를 나타내고, 문제에서 설명한 CCTV의 종류이다. 

CCTV의 최대 개수는 8개를 넘지 않는다.

출력

첫째 줄에 사각 지대의 최소 크기를 출력한다.


음.. 구현인가?

일단 각 CCTV의 상태의 경우의 수를 구하고,

그 상태별로 비쳐서 # 칠을 해야한다.

 

그냥 처음부터 끝까지 구현인건가?

시간 복잡도를 구해보자.

각 CCTV의 경우 최대 4가지의 경우의 수가 존재한다. (물론 2번은 두가지지만.)

CCTV는 최대 8개니까, 8개의 CCTV가 4가지 방향 중 하나를 비추는 모든 경우의 수는...

4x4x4x4x4x4x4x4 = 4의 8승 = 65,536 개!

 

그냥 계산하면 되나..?

아, 이거 조합의 DFS 문제구나.

여러 CCTV가 존재하고,

해당 CCTV마다 최대 4가지의 선택 가능한 방향이 존재한다.

 

모든 CCTV에 대해서 하나의 방향만을 선택하고, 그 선택 조합을 구하는 것이었다..


먼저, CCTV가 특정 방향을 비출 때 map을 바꾸고, 사각지대의 수를 줄여보자.

/**
     * x, y 좌표에서 시작해서 dir 방향으로 비춘다.
     * @param map 얕은 복사로 # 를 채워 넣는다.
     * @param x 시작하는 x좌표
     * @param y 시작하는 y좌표
     * @param dir 비출 방향
     * @param squareZone 비추기 전 사각지대의 수
     * @return 비춘 이후, 줄어든 사각지대
     */
    static int watching(int[][] map, int x, int y, int dir, int squareZone) {
        x += directions[0][dir];
        y += directions[1][dir];
        while (inRange(x, y)) {
            if (map[x][y] == 6) break;
            if (map[x][y] == 0) {
                map[x][y] = -1;
                squareZone --;
            }

            x += directions[0][dir];
            y += directions[1][dir];
        }
        return squareZone;
    }

DFS를 짜보자.

static void dfs(int cctvIdx, int[][] map, int squareZone) {
        if (cctvIdx == cctvLength) {
            result = Math.min(result, squareZone);
            return;
        }

        Cctv cctv = cctvList.get(cctvIdx);
        if (cctv.num == 1) {
            for (int dir=0; dir<4; dir++) {
                int[][] newMap = deepCopyMap(map);
                int newSquareZone = watching(newMap, cctv.x, cctv.y, dir, squareZone);
                dfs(cctvIdx + 1, newMap, newSquareZone);
            }
        }
        if (cctv.num == 2) {
            int[][] newMap = deepCopyMap(map);
            int newSquareZone = watching(newMap, cctv.x, cctv.y, 0, squareZone);
            newSquareZone = watching(newMap, cctv.x, cctv.y, 2, newSquareZone);
            dfs(cctvIdx + 1, newMap, newSquareZone);


            newMap = deepCopyMap(map);
            newSquareZone = watching(newMap, cctv.x, cctv.y, 1, squareZone);
            newSquareZone = watching(newMap, cctv.x, cctv.y, 3, newSquareZone);
            dfs(cctvIdx + 1, newMap, newSquareZone);
        }
        if (cctv.num == 3) {
            for (int dir=0; dir<4; dir++) {
                int[][] newMap = deepCopyMap(map);
                int newSquareZone = watching(newMap, cctv.x, cctv.y, dir, squareZone);
                newSquareZone = watching(newMap, cctv.x, cctv.y, (dir+1)%4, newSquareZone);
                dfs(cctvIdx + 1, newMap, newSquareZone);
            }
        }
        if (cctv.num == 4) {
            for (int dir=0; dir<4; dir++) {
                int[][] newMap = deepCopyMap(map);
                int newSquareZone = watching(newMap, cctv.x, cctv.y, dir, squareZone);
                newSquareZone = watching(newMap, cctv.x, cctv.y, (dir+1)%4, newSquareZone);
                newSquareZone = watching(newMap, cctv.x, cctv.y, (dir+2)%4, newSquareZone);
                dfs(cctvIdx + 1, newMap, newSquareZone);
            }
        }
        if (cctv.num == 5) {
            int[][] newMap = deepCopyMap(map);
            int newSquareZone = watching(newMap, cctv.x, cctv.y, 0, squareZone);
            newSquareZone = watching(newMap, cctv.x, cctv.y, 1, newSquareZone);
            newSquareZone = watching(newMap, cctv.x, cctv.y, 2, newSquareZone);
            newSquareZone = watching(newMap, cctv.x, cctv.y, 3, newSquareZone);
            dfs(cctvIdx + 1, newMap, newSquareZone);
        }
    }

 

이 코드를 짜면서 계~ 속 틀렸던 흔적. ^^,,

 

틀렸던 이유 1.  4번 CCTV를 돌릴때, 예를들어 `상/하/좌` 이렇게 비춰야 하는걸 `상/하/하` 이렇게 분기함.

틀렸던 이유 2. 근본적으로.. 방향이 잘못됨. 상하좌우 의 순대로 배정해놨었음 -> 상우하좌로 바꿈.

    static final int[][] directions = { // 상 하 좌 우
            {-1, 1, 0, 0},
            {0, 0, -1, 1}
    };
    
    // 이렇게 지정해놓고... 허 참..

 

틀렸던 이유3. 상우하좌로 바꿔놓는답시고 또 헷갈림.

// 상 우 하 좌 랍시고 지정해놓은 direction - 잘못됨
static final int[][] directions = { // 상 우 하 좌
    {-1, 0, 1, 0},
    { 0, 1, -1, 1 }
};

// 올바른 상 우 하 좌
static final int[][] directions = { // 상 우 하 좌
    {-1, 0, 1, 0},
    { 0, 1, 0, -1}
};

아니! 방향을! 왜이렇게 헷갈려하는거야!

그보다.. 방향에 대해서 상당히 코드가 지저분해 보이지 않는가?

방향 조합을 깔끔하게 가져가보자!! 규칙성을 잘 생각해 ~~~~~~

static int[][][] cctvType = { // 상0 우1 하2 좌3
        {},
        {{0}, {1}, {2}, {3}}, // 1번 cctv 상우하좌 따로따로 한방향씩 전부
        {{0, 2}, {1, 3}}, // 2번 cctv 상하 / 우좌
        {{0, 1}, {1, 2}, {2, 3}, {3, 0}}, // 3번 cctv 상우/우하/하좌/좌상
        {{0, 1, 2}, {1, 2, 3}, {2, 3, 0}, {3, 0, 1}}, // 4번 cctv 상우하/우하좌/하좌상/좌상우
        {{0, 1, 2, 3}}, // 5번 cctv 상우하좌 전부
};

static void dfs(int cctvIdx, int[][] map, int squareZone) {
    if (cctvIdx == cctvLength) {
        result = Math.min(result, squareZone);
        return;
    }

    Cctv cctv = cctvList.get(cctvIdx);
    int[][] type = cctvType[cctv.num];
    for (int[] round : type) {
        int[][] newMap = deepCopyMap(map);
        int newSquareZone = squareZone;

        for (int dir : round) {
            newSquareZone = watching(newMap, cctv.x, cctv.y, dir, newSquareZone);
        }

        dfs(cctvIdx + 1, newMap, newSquareZone);
    }
}

 

와우.. 엄청나게 깨끗해졌는걸..?


결론.

조합.. 그리고 방향 설정 ㅠㅠㅠ

 

조합 DFS 문제라는 것을 깨달아야 하는 것과

아니 ~~~~~~~~~~~~ 자꾸 방향 상태를 헷갈려 ~~~~~~~~~

(계속 방향설정을 틀렸다)

 

별것도 아닌 것같은데.. 사소한거에서 삐끗하버리면 당황하고야 만다... ㅠㅠ

 

여러가지 헷갈림 방지방법.

1. 주석으로 적어놓고 계속 확인하기.

// 0: ↑, 1: →, 2: ↓, 3: ←

 

2. 숫자로 direction 을 접근하지 말고 문자로 접근하도록 하기.

final int DX = 0, DY = 1;
final int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3;

directions[DX][UP];

 

3. 직관적으로 출력하면서 로직 짜기

String[] dirString = {"↑", "→", "↓", "←"};
System.out.println("현재 방향: " + dirString[dir]);
// 사실 이건 간간히 사용하던 방법이다.

 

4. 복잡한 방향 조합은 미리 생성해놓기.

int[][] cctv3 = {
    {UP, RIGHT},
    {RIGHT, DOWN},
    {DOWN, LEFT},
    {LEFT, UP}
};

최종 전체 코드

import java.io.*;
import java.util.*;

public class Main {

    static final int[][] directions = { // 상 우 하 좌
            {-1, 0, 1, 0},
            { 0, 1, 0, -1}
    };

    static int n;
    static int m;
    static int[][][] cctvType = { // 상0 우1 하2 좌3
            {},
            {{0}, {1}, {2}, {3}}, // 1번 cctv 상우하좌 전부
            {{0, 2}, {1, 3}}, // 2번 cctv 상하 / 우좌
            {{0, 1}, {1, 2}, {2, 3}, {3, 0}}, // 3번 cctv 상우/우하/하좌/좌상
            {{0, 1, 2}, {1, 2, 3}, {2, 3, 0}, {3, 0, 1}}, // 4번 cctv 상우하/우하좌/하좌상/좌상우
            {{0, 1, 2, 3}}, // 5번 cctv 상우하좌 전부
    };
    static List<Cctv> cctvList;
    static int cctvLength;
    static int result = Integer.MAX_VALUE;

    public static void main(String[] args) throws IOException {
//        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader reader = new BufferedReader(new FileReader("src/input.txt"));

        int[] inputs = Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        n = inputs[0];
        m = inputs[1];
        int[][] map = new int[n][m];
        cctvList = new ArrayList<>();
        int zero_count = 0;

        for (int i=0; i<n; i++) {
            inputs = Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
            for (int j=0; j<m; j++) {
                map[i][j] = inputs[j];
                if (inputs[j] == 0) zero_count ++;
                if (1 <= inputs[j] && inputs[j] < 6) cctvList.add(new Cctv(i, j, inputs[j]));
            }
        }

        cctvLength = cctvList.size();
        dfs(0, map, zero_count);
        System.out.println(result);
    }

    static void dfs(int cctvIdx, int[][] map, int squareZone) {
        if (cctvIdx == cctvLength) {
            result = Math.min(result, squareZone);
            return;
        }

        Cctv cctv = cctvList.get(cctvIdx);
        int[][] type = cctvType[cctv.num];
        for (int[] round : type) {
            int[][] newMap = deepCopyMap(map);
            int newSquareZone = squareZone;

            for (int dir : round) {
                newSquareZone = watching(newMap, cctv.x, cctv.y, dir, newSquareZone);
            }

            dfs(cctvIdx + 1, newMap, newSquareZone);
        }
    }

    static int[][] deepCopyMap(int[][] map) {
        int[][] newMap = new int[n][m];
        for (int i=0; i<n; i++) {
            for (int j=0; j<m; j++) {
                newMap[i][j] = map[i][j];
            }
        }
        return newMap;
    }

    /**
     * x, y 좌표에서 시작해서 dir 방향으로 비춘다.
     * @param map 얕은 복사로 # 를 채워 넣는다.
     * @param x 시작하는 x좌표
     * @param y 시작하는 y좌표
     * @param dir 비출 방향
     * @param squareZone 비추기 전 사각지대의 수
     * @return 비춘 이후, 줄어든 사각지대
     */
    static int watching(int[][] map, int x, int y, int dir, int squareZone) {
        x += directions[0][dir];
        y += directions[1][dir];
        while (inRange(x, y)) {
            if (map[x][y] == 6) break;
            if (map[x][y] == 0) {
                map[x][y] = -1;
                squareZone --;
            }

            x += directions[0][dir];
            y += directions[1][dir];
        }
        return squareZone;
    }

    static boolean inRange(int x, int y) {
        return 0 <= x && x < n && 0 <= y && y < m;
    }

    static void printMap(int[][] map) {
        for (int i=0; i<n; i++) {
            for (int j=0; j<m; j++) {
                System.out.print(map[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
    }

}

class Cctv {
    int x;
    int y;
    int num;

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

    @Override
    public String toString() {
        return "CCTV{" +
                "x=" + x +
                ",y=" + y +
                ",num=" + num + "}";
    }
}

+ Recent posts