본문 바로가기

개발/알고리즘

백준 알고리즘 14499

 

머리에서 주사위 빙글빙글 하다 머리 터질뻔...

 

입력 : 지도의 가로세로 크기(N, M), 주사위를 놓은 좌표(X, Y), 명령어 갯수(K), 지도 및 명령어

출력 : 한 명령어를 수행할 때마다 주사위 윗면의 숫자를 출력

 

풀이

1. 주사위를 코드로 표현. 전역변수로 저장

     0      North   0      0
     West Top      East  Bottom
     0      South   0      0
     0      Bottom 0      0

* Bottom이 두 개인 이유는 동.서로 굴릴 경우와 남.북으로 굴릴 경우 모두를 쉽게 표현하기 위함

2. 주사위를 동서남북으로 굴리는 함수를 정의
    -> 방향을 파라미터로 입력받는다.
    -> 동.서 방향은 2번 row을 좌우로 Shift, 남.북 방향은 2번 column을 위아래로 Shift
    -> Shift한 뒤에 두 Bottom값을 같게 맞춰준다.

3. 주사위를 굴리기 전.후 연산을 맡을 함수를 정의 (해놓고 보니까 그냥 main함수 for문 안에 해도 될듯?)
    -> 주사위가 지도 밖으로 나가는지 검사. 밖으로 나가면 함수 종료
    -> 주사위를 굴린 뒤 주사위 Bottom값과, 주사위와 만나는 지도의 칸의 값에 관한 연산 수행
    -> 모든 연산을 수행한 뒤 Top에 있는 값을 출력하고 함수 종료

 

소스코드

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
#include <iostream>
using namespace std;
 
int board[22][22];
int x, y;
int N, M;
int direction[4][2= {{0,1}, {0,-1}, {-10}, {1,0}};
int dice[4][4];
 
/*
 0:East 1:West 2:North 3:South
 
 0        North    0        0
 West    Top        East    Bottom
 0        South    0        0
 0        Bottom    0        0
*/
 
void rollDice(int direct){
    if(direct < 2){
        int temp[4];
        
        for(int i=0; i<4; i++)
            temp[i] = dice[1][(4 + i - direction[direct][1]) % 4];
        
        for(int i=0; i<4; i++)
            dice[1][i] = temp[i];
        
        dice[3][1= dice[1][3];
    }
    else {
        int temp[4];
        
        for(int i=0; i<4; i++)
            temp[i] = dice[(4 + i - direction[direct][0]) % 4][1];
        
        for(int i=0; i<4; i++)
            dice[i][1= temp[i];
        
        dice[1][3= dice[3][1];
    }
}
 
void moveDice(int direct){
    if(x + direction[direct][0< 0 || x + direction[direct][0>= N)
        return;
    else
        x += direction[direct][0];
    
    if(y + direction[direct][1< 0 || y + direction[direct][1>= M)
        return;
    else
        y += direction[direct][1];
    
    rollDice(direct);
    
    if(board[x][y] == 0)
        board[x][y] = dice[1][3];
    else if(board[x][y] != 0){
        dice[1][3= board[x][y];
        dice[3][1= board[x][y];
        board[x][y] = 0;
    }
    
    cout<<dice[1][1]<<endl;
}
 
int main() {
    int k;
 
    cin>>N>>M;
    cin>>x>>y;
    cin>>k;
    
    for(int i=0; i<N; i++)
        for(int j=0; j<M; j++)
            cin>>board[i][j];
    
    for(int i=0; i<k; i++){
        int direct;
        cin>>direct;
        
        moveDice(direct-1);
    }
    
    return 0;
}
cs

'개발 > 알고리즘' 카테고리의 다른 글

백준 알고리즘 14500  (0) 2019.02.19
백준 알고리즘 14501  (0) 2019.02.16
백준 알고리즘 13458  (0) 2019.02.16
백준 알고리즘 11931  (0) 2019.02.15
백준 알고리즘 12100  (0) 2019.02.14