BOJ : 6593 상범빌딩 C++

24609 단어 bojboj

상범빌딩

코드

#include <string>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int L,R,C;
    int dx[6] = {0, 1, 0, -1, 0, 0};
    int dy[6] = {1, 0, -1, 0, 0, 0};
    int dz[6] = {0, 0, 0, 0, 1, -1};
    while(true)
    {
        cin >> L >> R >> C;
        if(L == 0 and R == 0 and C == 0) break;
        char board[L][R][C];
        pair<int,pair<int,int>> start,end;
        int vis[L][R][C];
        /* 3차원 배열 초기화 */
        for(int z=0;z<L;z++)
            for(int y=0;y<R;y++)
            {
                fill(vis[z][y], vis[z][y]+C, -1);
                for(int x=0;x<C;x++)
                    {
                        cin >> board[z][y][x];
                        if(board[z][y][x] == 'S') start = {z,{y,x}};
                        if(board[z][y][x] == 'E') end = {z,{y,x}};
                    }
            }
        queue<pair<int,pair<int,int>>> q;

        q.push(start);
        int flag=0;
        vis[start.first][start.second.first][start.second.second] = 0;
        while(!q.empty())
        {
            auto cur = q.front(); q.pop();
            for(int dir=0;dir<6;dir++)
            {
                int nz = cur.first + dz[dir];
                int ny = cur.second.first + dy[dir];
                int nx = cur.second.second + dx[dir];
                if(nz<0 or nx<0 or ny<0 or nz>=L or ny>=R or nx>=C) continue;
                if(vis[nz][ny][nx] > -1 or board[nz][ny][nx] == '#' or board[nz][ny][nx] == 'S') continue;
                q.push({nz,{ny,nx}});
                vis[nz][ny][nx] = vis[cur.first][cur.second.first][cur.second.second] + 1;
                if(nz == end.first and ny == end.second.first and nx == end.second.second){
                    flag = 1;
                    break;
                }
            }
            if(flag == 1) break;
        }
         if(flag == 1) cout << "Escaped in "<< vis[end.first][end.second.first][end.second.second] <<" minute(s)."<<'\n';
        else cout<< "Trapped!"<<'\n';
    }
    return 0;
}
  • dx[] / dy[] / dz[] 3개의 범위를 잘 지정해야한다
    (6개에 방문 가능)
    int dx[6] = {0, 1, 0, -1, 0, 0};
    int dy[6] = {1, 0, -1, 0, 0, 0};
    int dz[6] = {0, 0, 0, 0, 1, -1};
  • fill을 이용한 3차원 배열 초기화
int vis[L][R][C];
for(int z=0;z<L;z++)
	for(int y=0;y<R;y++)
          fill(vis[z][y], vis[z][y]+C, -1);
          // 모든 요소를 -1로 초기화

좋은 웹페이지 즐겨찾기