알고리즘/백준

[백준 6593] 상범 빌딩 C++

겜도리도리 2021. 10. 1. 23:55
반응형

문제

백준 6593 상범 빌딩 C++

 

6593번: 상범 빌딩

당신은 상범 빌딩에 갇히고 말았다. 여기서 탈출하는 가장 빠른 길은 무엇일까? 상범 빌딩은 각 변의 길이가 1인 정육면체(단위 정육면체)로 이루어져있다. 각 정육면체는 금으로 이루어져 있어

www.acmicpc.net

풀이

2차원 배열로 bfs, dfs 문제를 푸는 경우가 많은데 이 문제는 3차원 배열로 풀어야해서 꽤 신선했습니다.

특별할 건 없고, 2차원 배열로 풀던걸 3차원으로 적용시키면 됩니다.

이동할 수 있는 지점은 상 / 하 / 좌 / 우 / 위 / 아래 (동서남북상하)의 6가지 경우입니다.

소스 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
 
// 동서남북상하
int dx[] = { 1-10000 };
int dy[] = { 001-100 };
int dz[] = { 00001-1 };
// z, y, x
int L, R, C;
char map[30][30][30];
bool visited[30][30][30];
 
struct pos
{
    int x;
    int y;
    int z;
    int t; // 시간
};
 
int bfs(int a, int b, int c) {
 
    memset(visited, 0sizeof(visited));
    visited[c][b][a] = true;
    queue<pos> q;
    q.push({ a, b, c, 0 });
    while (!q.empty()) {
        int x, y, z, time;
        x = q.front().x;
        y = q.front().y;
        z = q.front().z;
        time = q.front().t;
        q.pop();
        // 도착점 찾으면 return
        if (map[z][y][x] == 'E') {
            return time;
        }
        for (int i = 0; i < 6; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            int nz = z + dz[i];
            if (nx >= 0 && ny >= 0 && nz >= 0 && nx < C && ny < R && nz < L) {
                if (!visited[nz][ny][nx] && map[nz][ny][nx] != '#') {
                    visited[nz][ny][nx] = true;
                    q.push({ nx, ny, nz, time + 1 });
                }
            }
        }
   }
    return -1;
}
 
int main() {
    // 입력
    string str;
    int sz = 0, sy = 0, sx = 0;
    while (1) {
        cin >> L >> R >> C;
        if (L == 0 && R == 0 && C == 0)
            break;
        for (int i = 0; i < L; i++) {
            for (int j = 0; j < R; j++) {
                cin >> str;
                for (int k = 0; k < C; k++) {
                    if (str[k] == 'S') {
                        sz = i;
                        sy = j;
                        sx = k;
                    }
                    map[i][j][k] = str[k];
                }
            }
        }
        int ans = bfs(sx, sy, sz);
        // 탈출할 수 없으면
        if (ans == -1) {
            cout << "Trapped!" << '\n';
        }
        else {
            cout << "Escaped in " << ans << " minute(s)." << '\n';
        }
    }
    return 0;
}
cs
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 13023] ABCDE C++  (0) 2021.10.02
[백준 1038] 감소하는 수 C++  (0) 2021.10.01
[백준 17471] 게리맨더링 C++  (0) 2021.09.29
[백준 2668] 숫자고르기 C++  (0) 2021.09.28
[백준 9084] 동전 (C++)  (0) 2021.09.27