백준 13460번

구슬 탈출 2

Posted by ChoiCube84 on January 02, 2024 · 26 mins read

백준 13460번

오늘 풀어본 문제는 백준의 13460번 문제1이다. 문제 풀이에 사용한 언어는 C++ 이다.

solved.ac 기준 CLASS

CLASS 5

문제 정보

이 문제의 내용과 조건은 다음과 같다.

문제

스타트링크에서 판매하는 어린이용 장난감 중에서 가장 인기가 많은 제품은 구슬 탈출이다. 구슬 탈출은 직사각형 보드에 빨간 구슬과 파란 구슬을 하나씩 넣은 다음, 빨간 구슬을 구멍을 통해 빼내는 게임이다.

보드의 세로 크기는 $N$, 가로 크기는 $M$ 이고, 편의상 $1 \times 1$ 크기의 칸으로 나누어져 있다. 가장 바깥 행과 열은 모두 막혀져 있고, 보드에는 구멍이 하나 있다. 빨간 구슬과 파란 구슬의 크기는 보드에서 $1 \times 1$ 크기의 칸을 가득 채우는 사이즈이고, 각각 하나씩 들어가 있다. 게임의 목표는 빨간 구슬을 구멍을 통해서 빼내는 것이다. 이때, 파란 구슬이 구멍에 들어가면 안 된다.

이때, 구슬을 손으로 건드릴 수는 없고, 중력을 이용해서 이리 저리 굴려야 한다. 왼쪽으로 기울이기, 오른쪽으로 기울이기, 위쪽으로 기울이기, 아래쪽으로 기울이기와 같은 네 가지 동작이 가능하다.

각각의 동작에서 공은 동시에 움직인다. 빨간 구슬이 구멍에 빠지면 성공이지만, 파란 구슬이 구멍에 빠지면 실패이다. 빨간 구슬과 파란 구슬이 동시에 구멍에 빠져도 실패이다. 빨간 구슬과 파란 구슬은 동시에 같은 칸에 있을 수 없다. 또, 빨간 구슬과 파란 구슬의 크기는 한 칸을 모두 차지한다. 기울이는 동작을 그만하는 것은 더 이상 구슬이 움직이지 않을 때 까지이다.

보드의 상태가 주어졌을 때, 최소 몇 번 만에 빨간 구슬을 구멍을 통해 빼낼 수 있는지 구하는 프로그램을 작성하시오.

입력

첫 번째 줄에는 보드의 세로, 가로 크기를 의미하는 두 정수 $N, M$ $(3 \le N, M \le 10)$이 주어진다. 다음 $N$ 개의 줄에 보드의 모양을 나타내는 길이 $M$ 의 문자열이 주어진다. 이 문자열은 ‘.’, ‘#’, ‘O’, ‘R’, ‘B’ 로 이루어져 있다. ‘.’은 빈 칸을 의미하고, ‘#’은 공이 이동할 수 없는 장애물 또는 벽을 의미하며, ‘O’는 구멍의 위치를 의미한다. ‘R’은 빨간 구슬의 위치, ‘B’는 파란 구슬의 위치이다.

입력되는 모든 보드의 가장자리에는 모두 ‘#’이 있다. 구멍의 개수는 한 개 이며, 빨간 구슬과 파란 구슬은 항상 $1$ 개가 주어진다.

출력

최소 몇 번 만에 빨간 구슬을 구멍을 통해 빼낼 수 있는지 출력한다. 만약, $10$ 번 이하로 움직여서 빨간 구슬을 구멍을 통해 빼낼 수 없으면 $-1$ 을 출력한다.

풀이과정

1번째 시도

문제를 처음 보고 복잡한 구현문제라는 것을 알 수 있었다. 우선 구슬을 각 방향으로 기울였을 때 변한 상태로 만들어주는 함수들과, 이 함수들을 이용한 BFS 를 이용하여 가장 적은 횟수로 구슬을 탈출 시킬 수 있는 수를 저장하고 반환하도록 하였다.

코드는 다음과 같이 작성하였다.

#include <bits/stdc++.h>

#define EMPTY 0
#define WALL 1
#define GOAL 2
#define RED 3
#define BLUE 4

#define FAIL 0
#define SUCCESS 1
#define CONTINUE 2

using namespace std;

using Grid = array<array<int, 10>, 10>;

int N, M;
Grid board;

int escapeLength(void);

int left_tilt(Grid& curr);
int right_tilt(Grid& curr);
int up_tilt(Grid& curr);
int down_tilt(Grid& curr);

pair<pair<int, int>, pair<int, int>> findRB(Grid& curr);

int main(void) {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> N >> M;

    for (int i=0; i<N; i++) {
        string temp;
        cin >> temp;
        
        for (int j=0; j<M; j++) {
            switch (temp[j]) {
                case '.':
                    board[i][j] = EMPTY;
                    break;
                case '#':
                    board[i][j] = WALL;
                    break;
                case 'O':
                    board[i][j] = GOAL;
                    break;
                case 'R':
                    board[i][j] = RED;
                    break;
                case 'B':
                    board[i][j] = BLUE;
                    break;
            } 
        }
    }

    int result = escapeLength();
    if (result == INT_MAX) {
        cout << -1;
    }
    else {
        cout << escapeLength();
    }

    return 0;
}

int escapeLength(void) {
    int minimum = INT_MAX;

    queue<pair<Grid, int>> q;
    q.emplace(board, 0);

    while(!q.empty()) {
        auto curr = q.front();
        q.pop();

        if (curr.second >= 10 || minimum <= curr.second) {
            continue;
        }

        for (int i=0; i<4; i++) {
            Grid next = curr.first;
            int result;

            switch (i) {
                case 0:
                    result = left_tilt(next);
                    break;
                case 1:
                    result = right_tilt(next);
                    break;
                case 2:
                    result = up_tilt(next);
                    break;
                case 3:
                    result = down_tilt(next);
                    break;
            }

            switch (result) {
                case FAIL:
                    break;
                case SUCCESS:
                    minimum = min(minimum, curr.second + 1);
                    break;
                case CONTINUE:
                    q.emplace(next, curr.second + 1);
                    break;
            }
        }
    }

    return minimum;
}

int left_tilt(Grid& curr) {
    auto marbles = findRB(curr);
    auto red = marbles.first;
    auto blue = marbles.second;

    int newRed, newBlue;
    bool redIn = false;
    bool blueIn = false;

    if (red.second < blue.second) {
        for (newRed=red.second; curr[red.first][newRed - 1] == EMPTY; newRed--);
        if (curr[red.first][newRed - 1] == GOAL) {
            redIn = true;
        }
        curr[red.first][red.second] = EMPTY;
        if (!redIn) {
            curr[red.first][newRed] = RED;
        }

        for (newBlue=blue.second; curr[blue.first][newBlue - 1] == EMPTY; newBlue--);
        if (curr[blue.first][newBlue - 1] == GOAL) {
            blueIn = true;
        }
        curr[blue.first][blue.second] = EMPTY;
        if (!blueIn) {
            curr[blue.first][newBlue] = BLUE;
        }
    }
    else {
        for (newBlue=blue.second; curr[blue.first][newBlue - 1] == EMPTY; newBlue--);
        if (curr[blue.first][newBlue - 1] == GOAL) {
            blueIn = true;
        }
        curr[blue.first][blue.second] = EMPTY;
        if (!blueIn) {
            curr[blue.first][newBlue] = BLUE;
        }

        for (newRed=red.second; curr[red.first][newRed - 1] == EMPTY; newRed--);
        if (curr[red.first][newRed - 1] == GOAL) {
            redIn = true;
        }
        curr[red.first][red.second] = EMPTY;
        if (!redIn) {
            curr[red.first][newRed] = RED;
        }
    }

    if (blueIn) {
        return FAIL;
    }
    else if (redIn) {
        return SUCCESS;
    }
    else {
        return CONTINUE;
    }
}

int right_tilt(Grid& curr) {
    auto marbles = findRB(curr);
    auto red = marbles.first;
    auto blue = marbles.second;

    int newRed, newBlue;
    bool redIn = false;
    bool blueIn = false;

    if (red.second > blue.second) {
        for (newRed=red.second; curr[red.first][newRed + 1] == EMPTY; newRed++);
        if (curr[red.first][newRed + 1] == GOAL) {
            redIn = true;
        }
        curr[red.first][red.second] = EMPTY;
        if (!redIn) {
            curr[red.first][newRed] = RED;
        }

        for (newBlue=blue.second; curr[blue.first][newBlue + 1] == EMPTY; newBlue++);
        if (curr[blue.first][newBlue + 1] == GOAL) {
            blueIn = true;
        }
        curr[blue.first][blue.second] = EMPTY;
        if (!blueIn) {
            curr[blue.first][newBlue] = BLUE;
        }
    }
    else {
        for (newBlue=blue.second; curr[blue.first][newBlue + 1] == EMPTY; newBlue++);
        if (curr[blue.first][newBlue + 1] == GOAL) {
            blueIn = true;
        }
        curr[blue.first][blue.second] = EMPTY;
        if (!blueIn) {
            curr[blue.first][newBlue] = BLUE;
        }

        for (newRed=red.second; curr[red.first][newRed + 1] == EMPTY; newRed++);
        if (curr[red.first][newRed + 1] == GOAL) {
            redIn = true;
        }
        curr[red.first][red.second] = EMPTY;
        if (!redIn) {
            curr[red.first][newRed] = RED;
        }
    }

    if (blueIn) {
        return FAIL;
    }
    else if (redIn) {
        return SUCCESS;
    }
    else {
        return CONTINUE;
    }
}

int up_tilt(Grid& curr) {
    auto marbles = findRB(curr);
    auto red = marbles.first;
    auto blue = marbles.second;

    int newRed, newBlue;
    bool redIn = false;
    bool blueIn = false;

    if (red.first < blue.first) {
        for (newRed=red.first; curr[newRed - 1][red.second] == EMPTY; newRed--);
        if (curr[newRed - 1][red.second] == GOAL) {
            redIn = true;
        }
        curr[red.first][red.second] = EMPTY;
        if (!redIn) {
            curr[newRed][red.second] = RED;
        }

        for (newBlue=blue.first; curr[newBlue - 1][blue.second] == EMPTY; newBlue--);
        if (curr[newBlue - 1][blue.second] == GOAL) {
            blueIn = true;
        }
        curr[blue.first][blue.second] = EMPTY;
        if (!blueIn) {
            curr[newBlue][blue.second] = BLUE;
        }
    }
    else {
        for (newBlue=blue.first; curr[newBlue - 1][blue.second] == EMPTY; newBlue--);
        if (curr[newBlue - 1][blue.second] == GOAL) {
            blueIn = true;
        }
        curr[blue.first][blue.second] = EMPTY;
        if (!blueIn) {
            curr[newBlue][blue.second] = BLUE;
        }

        for (newRed=red.first; curr[newRed - 1][red.second] == EMPTY; newRed--);
        if (curr[newRed - 1][red.second] == GOAL) {
            redIn = true;
        }
        curr[red.first][red.second] = EMPTY;
        if (!redIn) {
            curr[newRed][red.second] = RED;
        }
    }

    if (blueIn) {
        return FAIL;
    }
    else if (redIn) {
        return SUCCESS;
    }
    else {
        return CONTINUE;
    }
}

int down_tilt(Grid& curr) {
    auto marbles = findRB(curr);
    auto red = marbles.first;
    auto blue = marbles.second;

    int newRed, newBlue;
    bool redIn = false;
    bool blueIn = false;

    if (red.first > blue.first) {
        for (newRed=red.first; curr[newRed + 1][red.second] == EMPTY; newRed++);
        if (curr[newRed + 1][red.second] == GOAL) {
            redIn = true;
        }
        curr[red.first][red.second] = EMPTY;
        if (!redIn) {
            curr[newRed][red.second] = RED;
        }

        for (newBlue=blue.first; curr[newBlue + 1][blue.second] == EMPTY; newBlue++);
        if (curr[newBlue + 1][blue.second] == GOAL) {
            blueIn = true;
        }
        curr[blue.first][blue.second] = EMPTY;
        if (!blueIn) {
            curr[newBlue][blue.second] = BLUE;
        }
    }
    else {
        for (newBlue=blue.first; curr[newBlue + 1][blue.second] == EMPTY; newBlue++);
        if (curr[newBlue + 1][blue.second] == GOAL) {
            blueIn = true;
        }
        curr[blue.first][blue.second] = EMPTY;
        if (!blueIn) {
            curr[newBlue][blue.second] = BLUE;
        }

        for (newRed=red.first; curr[newRed + 1][red.second] == EMPTY; newRed++);
        if (curr[newRed + 1][red.second] == GOAL) {
            redIn = true;
        }
        curr[red.first][red.second] = EMPTY;
        if (!redIn) {
            curr[newRed][red.second] = RED;
        }
    }

    if (blueIn) {
        return FAIL;
    }
    else if (redIn) {
        return SUCCESS;
    }
    else {
        return CONTINUE;
    }
}

pair<pair<int, int>, pair<int, int>> findRB(Grid& curr) {
    pair<int, int> red, blue;

    for (int i=0; i<N; i++) {
        for (int j=0; j<M; j++) {
            if (curr[i][j] == RED) {
                red = make_pair(i, j);
            }
            else if (curr[i][j] == BLUE) {
                blue = make_pair(i, j);
            }
        }
    }

    return make_pair(red, blue);
}

그러자 모든 테스트 케이스를 통과하고 정답이 나오는 것을 확인할 수 있었다.

마무리

문제를 해결한 원리 자체는 그렇게 어렵지 않은데, 세부 조건이 워낙 많다보니 구현하는데 너무 오랜 시간이 걸려버렸다. 채점 조차도 엄청 느리게 이루어져 마음이 조마조마 했지만, 다행히 한 번에 통과해주어 기뻤다.

역시 CLASS 5 문제들은 다른 것 같다. 정말 붙잡고 어느 정도 시간을 갈아넣어야 풀리는 문제들이 많은 것 같다… 앞으로의 여정이 조금은 걱정된다.

오늘의 PS는 여기까지!


1: https://www.acmicpc.net/problem/13460