[BOJ] (6593) 상범 빌딩 (Java)

zerokick·2023년 4월 26일
0

Coding Test

목록 보기
92/120
post-thumbnail

(6593) 상범 빌딩 (Java)


시간 제한메모리 제한제출정답맞힌 사람정답 비율
1 초128 MB163906127480437.048%

문제

당신은 상범 빌딩에 갇히고 말았다. 여기서 탈출하는 가장 빠른 길은 무엇일까? 상범 빌딩은 각 변의 길이가 1인 정육면체(단위 정육면체)로 이루어져있다. 각 정육면체는 금으로 이루어져 있어 지나갈 수 없거나, 비어있어서 지나갈 수 있게 되어있다. 당신은 각 칸에서 인접한 6개의 칸(동,서,남,북,상,하)으로 1분의 시간을 들여 이동할 수 있다. 즉, 대각선으로 이동하는 것은 불가능하다. 그리고 상범 빌딩의 바깥면도 모두 금으로 막혀있어 출구를 통해서만 탈출할 수 있다.

당신은 상범 빌딩을 탈출할 수 있을까? 만약 그렇다면 얼마나 걸릴까?

입력

입력은 여러 개의 테스트 케이스로 이루어지며, 각 테스트 케이스는 세 개의 정수 L, R, C로 시작한다. L(1 ≤ L ≤ 30)은 상범 빌딩의 층 수이다. R(1 ≤ R ≤ 30)과 C(1 ≤ C ≤ 30)는 상범 빌딩의 한 층의 행과 열의 개수를 나타낸다.

그 다음 각 줄이 C개의 문자로 이루어진 R개의 행이 L번 주어진다. 각 문자는 상범 빌딩의 한 칸을 나타낸다. 금으로 막혀있어 지나갈 수 없는 칸은 '#'으로 표현되고, 비어있는 칸은 '.'으로 표현된다. 당신의 시작 지점은 'S'로 표현되고, 탈출할 수 있는 출구는 'E'로 표현된다. 각 층 사이에는 빈 줄이 있으며, 입력의 끝은 L, R, C가 모두 0으로 표현된다. 시작 지점과 출구는 항상 하나만 있다.

출력

각 빌딩에 대해 한 줄씩 답을 출력한다. 만약 당신이 탈출할 수 있다면 다음과 같이 출력한다.

Escaped in x minute(s).
여기서 x는 상범 빌딩을 탈출하는 데에 필요한 최단 시간이다.

만일 탈출이 불가능하다면, 다음과 같이 출력한다.

Trapped!

예제 입력 1

3 4 5
S....
.###.
.##..
###.#

#####
#####
##.##
##...

#####
#####
#.###
####E

\1 3 3
\S##
#E#
###

\0 0 0

예제 출력 1

Escaped in 11 minute(s).
Trapped!

출처

Contest > University of Ulm Local Contest > University of Ulm Local Contest 1997 D번

문제의 오타를 찾은 사람: hwajin, madcatlove
데이터를 추가한 사람: speedlin1964
문제를 번역한 사람: yh0413

알고리즘 분류

그래프 이론
그래프 탐색
너비 우선 탐색

Solution

import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {
    public static int l, r, c;
    public static char[][][] bd;
    public static int[][][] time;
    public static class Pair {
        int z, x, y;
        Pair(int z, int x, int y) {
            this.z = z;
            this.x = x;
            this.y = y;
        }
    }
    public static Queue<Pair> q;
    public static int[] dz = {0, 0, 0, 0, 1, -1};
    public static int[] dx = {1, 0, -1, 0, 0, 0};
    public static int[] dy = {0, -1, 0, 1, 0, 0};

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        StringTokenizer st = new StringTokenizer(br.readLine());

        l = Integer.parseInt(st.nextToken());
        r = Integer.parseInt(st.nextToken());
        c = Integer.parseInt(st.nextToken());

        while(l > 0) {
            // 빌딩, 방문 시간 세팅
            bd = new char[l][r][c];
            time = new int[l][r][c];
            q = new LinkedList<Pair>();
            
            for(int k = 0; k < l; k++) {
                for(int i = 0; i < r; i++) {
                    String[] strArr = br.readLine().split("");
                    for(int j = 0; j < c; j++) {
                        char ch = strArr[j].charAt(0);
                        bd[k][i][j] = ch;
                        if(ch == 'S') {
                            q.offer(new Pair(k, i, j));
                            time[k][i][j] = 0;
                        } else {
                            time[k][i][j] = -1;
                        }
                    }
                }
                br.readLine();
            }

            // 탈출 시작
            int result = findEscape();
            if(result > -1) {
                bw.write("Escaped in " + result + " minute(s)." + "\n");
            } else {
                bw.write("Trapped!" + "\n");
            }

            // 다음 테스트 케이스 세팅
            st = new StringTokenizer(br.readLine());
            l = Integer.parseInt(st.nextToken());
            r = Integer.parseInt(st.nextToken());
            c = Integer.parseInt(st.nextToken());
        }

        bw.flush();
        bw.close();
    }

    public static int findEscape() {
        while(!q.isEmpty()) {
            Pair pollCell = q.poll();

            // 탈출구에 도착하면
            if(bd[pollCell.z][pollCell.x][pollCell.y] == 'E') return time[pollCell.z][pollCell.x][pollCell.y];

            // 인접 칸 탐색 (하, 좌, 우, 상, 하(3차원), 상(3차원))
            for(int k = 0; k < 6; k++) {
                int nz = pollCell.z + dz[k];
                int nx = pollCell.x + dx[k];
                int ny = pollCell.y + dy[k];

                // 빌딩 범위를 벗어나거나, 금으로 막혀있거나, 이미 방문한 칸이면 skip
                if(isNotRange(nz, nx, ny) || bd[nz][nx][ny] == '#' || time[nz][nx][ny] > -1) continue;

                q.offer(new Pair(nz, nx, ny));
                time[nz][nx][ny] = time[pollCell.z][pollCell.x][pollCell.y] + 1;
            }
        }

        // 이동이 끝난 후에도 탈출구에 도착못했으므로 fail
        return -1;
    }

    public static boolean isNotRange(int z, int x, int y) {
        return (z < 0 || z >= l || x < 0 || x >= r || y < 0 || y >= c) ? true : false;
    }
}

Feedback

profile
Opportunities are never lost. The other fellow takes those you miss.

0개의 댓글