구슬 탈출 2

Huisu·2023년 10월 31일
0

Coding Test Practice

목록 보기
57/98
post-thumbnail

문제

13460번: 구슬 탈출 2

문제 설명

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

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

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

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

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

제한 사항

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

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

입출력 예

입력출력
5 5
#####
#..B#
#.#.#
#RO.#
#####1
7 7
#######
#...RB#
#.#####
#.....#
#####.#
#O....#
#######5
7 7
#######
#..R#B#
#.#####
#.....#
#####.#
#O....#
#######5
10 10
##########
#R#...##B#
#...#.##.#
#####.##.#
#......#.#
#.######.#
#.#....#.#
#.#.#.#..#
#...#.O#.#
##########-1
3 7
#######
#R.O.B#
#######1
10 10
##########
#R#...##B#
#...#.##.#
#####.##.#
#......#.#
#.######.#
#.#....#.#
#.#.##...#
#O..#....#
##########7
3 10
##########
#.O....RB#
##########-1

추가 TC

입력출력
3 6
######
#.ORB#
######-1
8 8
########
#.####.#
#...#B##
#.##.R.#
######.#
##.##O.#
###.##.#
########7
4 6
######
#R####
#B..O#
######
ANS:-1-1
4 6
######
#R#O##
#B...#
######4

아이디어

BFS에 브루트포스가 섞인 문제

red와 blue가 한꺼번에 움직이기 때문에 방향키를 조사하는 4번의 dRow, dCol 반복문 안에서 각각 끝까지 와일문을 돌려야 한다

여기서 레드가 구멍에 들어갈 때, 블루가 구멍에 들어갈 때를 조사하고

마지막으로 제일 중요한 두 공의 다음 위치가 같을 때 위치 조정 과정을 해 준다

예를 들어 벽|레드|길|블루 순서로 있을 때 왼쪽으로 기울이면 벽|레드, 블루가 된다

이럴 때 레드가 더 왼쪽에 있으니까 벽|레드|블루가 되도록 위치를 조정해 주는 것이다

이 과정을 모든 방향마다 해 준다

방문은 레드와 블루를 모두 체크하도록 boolean[][][][]로 해 줘야 한다

제출 코드


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

class Marble {
    int redRow;
    int redCol;
    int blueRow;
    int blueCol;
    int count;
    Marble(int redCol, int redRow, int blueCol, int blueRow, int count) {
        this.redCol = redCol;
        this.redRow = redRow;
        this.blueCol = blueCol;
        this.blueRow = blueRow;
        this.count = count;
    }
}

public class one13460 {
    private static int n;
    private static int m;
    private static char[][] map;
    private static boolean[][][][] visited;
    private static int holeCol, holeRow;
    private static Marble red, blue;
    private static int MAX_COUNT = 10;
    private static int[] dCol = new int[] {-1, 0, 1, 0};
    private static int[] dRow = new int[] {0, -1, 0, 1};
    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer infoToken = new StringTokenizer(reader.readLine());
        n = Integer.parseInt(infoToken.nextToken());
        m = Integer.parseInt(infoToken.nextToken());

        visited = new boolean[n][m][n][m];
        map = new char[n][m];
        for (int i = 0; i < n; i++) {
            String line = reader.readLine();
            for (int j = 0; j < m; j++) {
                map[i][j] = line.charAt(j);
                if (map[i][j] == 'R') {
                    red = new Marble(i, j, 0, 0, 0);
                } else if (map[i][j] == 'B') {
                    blue = new Marble(0, 0, i, j, 0);
                } else if (map[i][j] == 'O') {
                    holeCol = i;
                    holeRow = j;
                }
            }
        }
        System.out.println(bfs());
        reader.close();
    }

    private static int bfs() {
        Queue<Marble> toVisit = new LinkedList<>();
        toVisit.add(new Marble(red.redCol, red.redRow, blue.blueCol, blue.blueRow, 1));
        visited[red.redCol][red.redRow][blue.blueCol][blue.blueRow] = true;

        while (!toVisit.isEmpty()) {
            Marble marble = toVisit.poll();

            int nowRedCol = marble.redCol;
            int nowRedRow = marble.redRow;
            int nowBlueCol = marble.blueCol;
            int nowBlueRow = marble.blueRow;
            int nowCount = marble.count;

            if (nowCount > MAX_COUNT) {
                return -1;
            }

            for (int i = 0; i < 4; i++) {
                int nextRedCol = nowRedCol;
                int nextRedRow = nowRedRow;
                int nextBlueCol = nowBlueCol;
                int nextBlueRow = nowBlueRow;

                boolean isRedHole = false;
                boolean isBlueHole = false;

                while (map[nextRedCol + dCol[i]][nextRedRow + dRow[i]] != '#') {
                    nextRedCol += dCol[i];
                    nextRedRow += dRow[i];

                    if (nextRedCol == holeCol && nextRedRow == holeRow) {
                        isRedHole = true;
                        break;
                    }
                }

                while (map[nextBlueCol + dCol[i]][nextBlueRow + dRow[i]] != '#') {
                    nextBlueCol += dCol[i];
                    nextBlueRow += dRow[i];

                    if (nextBlueCol == holeCol && nextBlueRow == holeRow) {
                        isBlueHole = true;
                        break;
                    }
                }

                if (isBlueHole) continue;
                if (isRedHole && !isBlueHole) return nowCount;

                if (nextRedCol == nextBlueCol && nextRedRow == nextBlueRow) {
                    if (i == 0) {
                        if (nowRedCol < nowBlueCol) nextBlueCol -= dCol[i];
                        else nextRedCol -= dCol[i];
                    } else if (i == 1) {
                        if (nowRedRow < nowBlueRow) nextBlueRow -= dRow[i];
                        else nextRedRow -= dRow[i];
                    } else if (i == 2) {
                        if (nowRedCol < nowBlueCol) nextRedCol -= dCol[i];
                        else nextBlueCol -= dCol[i];
                    } else {
                        if (nowRedRow < nowBlueRow) nextRedRow -= dRow[i];
                        else nextBlueRow -= dRow[i];
                    }
                }
                if (!visited[nextRedCol][nextRedRow][nextBlueCol][nextBlueRow]) {
                    visited[nextRedCol][nextRedRow][nextBlueCol][nextBlueRow] = true;
                    toVisit.add(new Marble(nextRedCol, nextRedRow, nextBlueCol, nextBlueRow, nowCount + 1));
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) throws IOException {
        new one13460().solution();
    }
}

0개의 댓글