프로그래밍/알고리즘

BOJ 14499 · 주사위 굴리기

반응형


알고리즘 분류 : 시뮬레이션  


문제에 주어진 조건에 따라 주사위를 굴리는 문제다.


  • 먼저 주사위의 숫자를 임의로 고정시킨다.
  • 동서남북 방향에 따라 바뀌는 주사위의 숫자를 설정한다.
  • 방향에 따라 시뮬레이션 한다.
  • 아래의 그림을 참조. 주사위 모양에서 0이 윗면이고, 5가 바닥면이다.





C++ 소스코드


#include <cstdio>

int n, m, x, y, k;
int a[20][20];
int dice[6], temp[6];
const int direct[4][6] = {
    {2, 1, 5, 0, 4, 3},
    {3, 1, 0, 5, 4, 2},
    {4, 0, 2, 3, 5, 1},
    {1, 5, 2, 3, 0, 4}
};
const int dx[] = {0, 0, -1, 1}, dy[] = {1, -1, 0, 0};

void solve() {
    while (k--) {
        int d;
        scanf("%d", &d); d--;
        x += dx[d], y += dy[d];
        if (x < 0 || x >= n || y < 0 || y >= m) {
            x -= dx[d], y -= dy[d];
            continue;
        }
        for (int i=0; i<6; i++) {
            temp[i] = dice[i];
        }
        for (int i=0; i<6; i++) {
            dice[i] = temp[direct[d][i]];
        }
        if (a[x][y]) {
            dice[5] = a[x][y];
            a[x][y] = 0;
        } else {
            a[x][y] = dice[5];
        }
        printf("%d\n", dice[0]);
    }
}

int main() {
    scanf("%d %d %d %d %d", &n, &m, &x, &y, &k);
    for (int i=0; i<n; i++) {
        for (int j=0; j<m; j++) {
            scanf("%d", &a[i][j]);
        }
    }
    solve();
    return 0;
}




Python 3 소스코드


direct = [
    (2, 1, 5, 0, 4, 3),
    (3, 1, 0, 5, 4, 2),
    (4, 0, 2, 3, 5, 1),
    (1, 5, 2, 3, 0, 4)
]
dx, dy = (0, 0, -1, 1), (1, -1, 0, 0)
n, m, x, y, k = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
c = list(map(int, input().split()))
dice, temp = [0]*6, [0]*6

for i in range(k):
    d = c[i]-1
    x, y = x+dx[d], y+dy[d]
    if x < 0 or x >= n or y < 0 or y >= m:
        x, y = x-dx[d], y-dy[d]
        continue
    for j in range(6):
        temp[j] = dice[j]
    for j in range(6):
        dice[j] = temp[direct[d][j]]
    if a[x][y]:
        dice[5] = a[x][y]
        a[x][y] = 0
    else:
        a[x][y] = dice[5]
    print(dice[0])




참고



반응형