6593 - 상범빌딩

Byung Seon Kang·2022년 10월 21일

코드

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

class Main {
    static int floor, rows, cols,startY,startX,startZ;
    static int[] dy = {-1,0,1,0,0,0};
    static int[] dx = {0,1,0,-1,0,0};
    static int[] dz = {0,0,0,0,-1,1};
    static char[][][] map;

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        while(true){
            StringTokenizer st = new StringTokenizer(br.readLine());
            floor = Integer.parseInt(st.nextToken());
            rows = Integer.parseInt(st.nextToken());
            cols = Integer.parseInt(st.nextToken());
            if(floor==0 && rows==0 && cols==0)break;

            map = new char[floor][rows][cols];

            for(int i=0; i<floor; i++){
                String input;
                for(int j=0; j<rows; j++){
                    input = br.readLine();
                    for(int k=0; k<cols; k++){
                        map[i][j][k] = input.charAt(k);
                        if(map[i][j][k]=='S'){
                            startZ = i;
                            startY = j;
                            startX = k;
                        }
                    }
                }
                br.readLine();
            }

            int result = bfs();
            if(result!=-1)
                sb.append("Escaped in ").append(result).append(" minute(s).\n");
            else
                sb.append("Trapped!\n");
        }

        System.out.println(sb);
    }

    private static int bfs() {
        Queue<int[]> q = new ArrayDeque<>();
        q.add(new int[]{startZ,startY,startX, 0});
        map[startZ][startY][startX] = '#';

        while(!q.isEmpty()){
            int[] current = q.poll();
            int newDist = current[3] + 1;
            for(int i=0; i<6; i++){
                int nz = dz[i] + current[0];
                int ny = dy[i] + current[1];
                int nx = dx[i] + current[2];

                if(nz<0 || nz>=floor || ny<0 || ny>=rows || nx<0 || nx>=cols)continue;
                if(map[nz][ny][nx]=='E')return newDist;
                if(map[nz][ny][nx]=='#')continue;
                q.add(new int[]{nz, ny, nx, newDist});
                map[nz][ny][nx] = '#';
            }
        }
        return -1;
    }
}
  • BFS 3차원으로 풀었다.
  • 처음엔 count해주는 배열 따로 만들었는데 메모리 초과 발생했었다.
profile
왜 필요한지 질문하기

0개의 댓글