민준이 블로그에영

[BOJ - 14499] 주사위 굴리기 (C++) 본문

Baekjoon(C++)/시뮬레이션

[BOJ - 14499] 주사위 굴리기 (C++)

alswns8081 2025. 4. 5. 15:33

  • 1, 2, 3, 4가 각각 동서남북을 의미하므로 dx, dy 배열의 인덱스를 사용해 해당 명령을 처리
  • 각 위치에 따라서 동서남북을 이동할 때 위치가 바뀌므로 고정된 좌표를 사용하기로 결정
    • 아래 사진의 1, 2, 3, 4, 5, 6을 배열의 인덱스로 설정해 0, 1, 2, 3, 4, 5로 변경
    • 0은 현재 주사위의 바닥, 5는 현재 주사위의 위로, 보이는 면으로 설정
    • 동, 서, 남, 북 각각의 경우를 함수로 구현해 dice의 위치를 변경해줌

  • 외에는 현재 grid 배열의 값이 0인 경우 dice에 있는 값을 복사
  • 0이 아닌 경우에는 dice에 해당 값을 복사하고 grid의 값을 0으로 초기화

 

문제상황

테스트 케이스가 제대로 동작하지 않는 문제가 발생 -> 코드를 잘못 구현했다고 판단

int nx = x + dx[command[i]];
int ny = y + dy[command[i]];
  • command[i]를 배열의 인덱스로 받았어야 했는데 i로 처리해서 문제가 발생했었음;;

 

코드

#include <iostream>
#include <vector>
using namespace std;

int N, M, x, y, K;
vector<vector<int>> grid;
vector<int> command;

// 동, 서, 북, 남
int dx[5] = {0, 0, 0, -1, 1};
int dy[5] = {0, 1, -1, 0, 0};

int dice[6] = {0, 0, 0, 0, 0, 0};

void move_north() {
    int temp = dice[0];
    dice[0] = dice[1];
    dice[1] = dice[5];
    dice[5] = dice[4];
    dice[4] = temp;
}

void move_south() {
    int temp = dice[0];
    dice[0] = dice[4];
    dice[4] = dice[5];
    dice[5] = dice[1];
    dice[1] = temp;
}

void move_east() {
    int temp = dice[0];
    dice[0] = dice[2];
    dice[2] = dice[5];
    dice[5] = dice[3];
    dice[3] = temp;
}

void move_west() {
    int temp = dice[0];
    dice[0] = dice[3];
    dice[3] = dice[5];
    dice[5] = dice[2];
    dice[2] = temp;
}

// 바깥으로 나가는 명령을 제외
bool inArea(int cur_x, int cur_y) {
    return cur_x>=0 && cur_x<N && cur_y>=0 && cur_y<M;
}

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

    cin >> N >> M >> x >> y >> K;
    grid.resize(N, vector<int>(M));

    for (int i=0; i<N; i++) {
        for (int j=0; j<M; j++) cin >> grid[i][j];
    }

    command.resize(K);
    for (int i=0; i<K; i++) {
        cin >> command[i];
    }

    for (int i =0; i < K; i++) {
        int nx = x + dx[command[i]];
        int ny = y + dy[command[i]];

        if (!inArea(nx, ny)) continue;

        switch (command[i]) {
            case 1:
                move_east();
                break;
            case 2:
                move_west();
                break;
            case 3:
                move_north();
                break;
            case 4:
                move_south();
                break;
        }

        if (grid[nx][ny] == 0) {
            grid[nx][ny] = dice[0];
        } else {
            dice[0] = grid[nx][ny];
            grid[nx][ny] = 0;
        }

        x = nx; y = ny;
        cout << dice[5] << '\n';
    }

    return 0;
}

 

링크

https://www.acmicpc.net/problem/14499

'Baekjoon(C++) > 시뮬레이션' 카테고리의 다른 글

[BOJ - 5212] 지구 온난화 (C++)  (1) 2025.04.08
[BOJ - 8911] 거북이(C++)  (0) 2025.04.07
[BOJ - 16234] 인구 이동 (C++)  (0) 2025.04.04
[BOJ - 14503] 로봇 청소기 (C++)  (0) 2025.03.31
[BOJ - 23351] 물 주기(C++)  (0) 2025.02.04