본문 바로가기

공부/알고리즘 문제풀이

[삼성 기출 문제] 백준 14499 주사위 굴리기

반응형

문제 링크


어떻게 풀까?


시뮬레이션 문제입니다! 문제의 순서를 정확히 파악해서 문제가 요구하는 데로 구현하면 종료됩니다!


특히, 주사위가 돌아갈 때마다 주사위의 면이 어떻게 변하는지, 맵은 어떻게 변하는지를 잘 조절하시면 됩니다!


정육면체가 위, 아래, 왼쪽, 오른쪽으로 이동할때마다 면이 어떻게 변하는지를 switch 문으로 구분해 줍니다.


위나 아래로 굴러갈때에는 아래 그림 처럼 4개의 면을 순서대로 이동하면 되고,




오른쪽이나 왼쪽으로 굴러갈때에는 아래 그림처럼 4개의 면을 순서대로 이동하면 됩니다! 


이렇게 회전한 뒤에 맵의 면이 0일 경우와 아닐 경우를 구분해서 주사위 면의 바닥과 맵의 값을 변경해 주시면 됩니다!

그리고 주사위의 윗면에 적힌 수를 출력하면 되죠!


다만, 맵의 경계 밖이라면 함수에서 리턴해서 위치가 변경되지도 않고, 주사위 윗면도 출력하지 않도록 합시다.


코드


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
88
89
90
91
92
93
94
95
96
97
#include<iostream>
 
using namespace std;
 
struct RollDice_Dice
{
    int n; int m;
    int up,down,left,right,front,rear;
    int map[22][22];
    int positionX;
    int positionY;
    
    const int dx[5= {0,1,-1,0,0};
    const int dy[5= {0,0,0,-1,1};
    RollDice_Dice()
    {
        for(int i =0;i<22;i++)
        {
            for(int j = 0 ; j<22; j++) map[i][j] = -1;
        }
        down = left = right = front = rear = up = 0;
    }
    int print()
    {
       cout << up <<'\n'
    }
    
    void change()
    {
        if(map[positionY][positionX])
        {
            down = map[positionY][positionX];
            map[positionY][positionX] = 0;
        }
        else
        {
            map[positionY][positionX] = down;
        }
    }
    bool roll(int d)
    {
        int nextX = positionX + dx[d], nextY = positionY + dy[d];
        
        if(map[nextY][nextX] == -1return false ;
        positionX = nextX;
        positionY = nextY;
        int temp;
        temp = up;
        switch(d)
        {
            case 1:
            up = left; left = down; down = right;
            right = temp;
            break;
            case 2:
            up = right; right = down; down = left;
            left = temp;
            break;
            case 3:
            up = frontfront = down; down = rear;
            rear = temp;
            break;
            case 4:
            up = rear; rear = down; down = front;
            front = temp;
            break;
 
 
        }
        change();
        print();
    }
} RollDice_dice;
 
int main()
{
    int k;
    int **map = (int**)RollDice_dice.map;
    int&= RollDice_dice.n;
    int &= RollDice_dice.m;
    cin >> RollDice_dice.n >> RollDice_dice.m >> RollDice_dice.positionY >> RollDice_dice.positionX >> k;
    RollDice_dice.positionX++; RollDice_dice.positionY++;
    for(int i = 1 ; i<=n;i++)
    {
        for(int j = 1 ; j<=m; j++)
        {
            cin >> RollDice_dice.map[i][j];
        }
    }
    int comm;
    for(int i  = k;i--;)
    {
        cin >> comm;
        RollDice_dice.roll(comm);
    }
    return 0;
}
cs


시간복잡도


시간복잡도는 명령의 개수인 O(K)입니다.

반응형