문제 링크

  • 나의 풀이

bfs를 이용하여 풀었다.

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <queue>

using namespace std;

constexpr int dl[6] = { -1, 1, 0, 0, 0, 0 };
constexpr int dr[6] = { 0, 0, -1, 1, 0, 0 };
constexpr int dc[6] = { 0, 0, 0, 0, -1, 1 };

struct pos {
    int l, r, c, t;
};

char bd[30][30][30];
int ck[30][30][30];
int L, R, C;
pos s, e;

int solve()
{
    queue<pos> q;
    q.push(s);
    ck[s.l][s.r][s.c] = 1;

    int ret = -1;

    while (!q.empty())
    {
        pos f = q.front();
        q.pop();

        if (f.l == e.l && f.r == e.r && f.c == e.c)
        {
            ret = f.t;
            break;
        }

        f.t += 1;

        for (int d = 0; d < 6; d++)
        {
            pos npos = f;
            npos.l += dl[d];
            npos.r += dr[d];
            npos.c += dc[d];

            if (npos.l < 0 || npos.l >= L || npos.r < 0 || npos.r >= R || npos.c < 0 || npos.c >= C
                || ck[npos.l][npos.r][npos.c] || bd[npos.l][npos.r][npos.c] == '#')
                continue;
            
            ck[npos.l][npos.r][npos.c] = 1;
            q.push(npos);
        }
    }

    return ret;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    string tmp;

    while (true)
    {
        cin >> L >> R >> C;

        if (!L)
            break;

        for(int l = 0; l < L; l++)
        {
            for (int r = 0; r < R; r++)
            {
                cin >> tmp;
                for (int c = 0; c < C; c++)
                {
                    bd[l][r][c] = tmp[c];
                    ck[l][r][c] = 0;
                    if (tmp[c] == 'S')
                    {
                        s = { l, r, c, 0 };
                    }
                    if (tmp[c] == 'E')
                    {
                        e = { l, r, c, 0 };
                    }
                }
            }
        }

        int ret = solve();
        if (ret == -1)
            cout << "Trapped!\n";
        else
            cout << "Escaped in " << ret << " minute(s).\n";
    }

    return 0;
}

댓글남기기