본문 바로가기
Programming/Algorithm

백준 2174 로봇 시뮬레이션

by OKOK 2018. 4. 4.

1. 문제를 명확하게 이해하는 것이 우선입니다.

2. 하나의 명령을 먼저 모두 수행한다!

3. 로봇을 저장하는 구조체와

4. 명령어를 저장하는 구조체가 필요하고

5. 로봇의 위치를 나타내는 맵이 필요합니다.


그리고 시뮬레이션 돌려주면 됩니다.


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
/*
2018.04.04.1600
*/
 
#include <iostream>
#include <algorithm>
using namespace std;
#define SIZE 105 // 105
 
struct point {
    int x, y;
    int dir;
};
point robot[SIZE];
 
struct command {
    int num;
    char com;
    int rep;
};
command store[SIZE];
 
int x, y, nx, ny;
char input_dir;
int dir;
int A, B, N, M;
int dx[] = {0,1,0,-1}; // 동 남 서 북
int dy[] = {1,0,-1,0};
int map[SIZE][SIZE];
 
 
 
void problemIn() {
    cin >> A >> B; // B 가 행 A가 열 입니다.
    cin >> N >> M;
    for (int i = 1; i <= N; i++) {
        cin >> robot[i].y >> robot[i].x >> input_dir;
        robot[i].x = (B - robot[i].x);
        robot[i].y = (robot[i].y-1);
        if (input_dir == 'E') robot[i].dir = 0;
        else if (input_dir == 'S') robot[i].dir = 1;
        else if (input_dir == 'W') robot[i].dir = 2;
        else if (input_dir == 'N') robot[i].dir = 3;
        map[robot[i].x][robot[i].y] = i;
    }
    for (int i = 1; i <= M; i++) {
        cin >> store[i].num >> store[i].com >> store[i].rep;
    }
}
 
void solve() {
 
    for (int i = 1; i <= M; i++) {
        int rep_num = store[i].rep;
 
        while (rep_num--) {        
            if (store[i].com == 'F') {
                x = robot[store[i].num].x;
                y = robot[store[i].num].y;
                dir = robot[store[i].num].dir;
                nx = x + dx[dir];
                ny = y + dy[dir];
 
                if (nx < 0 || ny < 0 || nx >= B || ny >= A) {
                    cout << "Robot " << store[i].num << " crashes into the wall" << endl;
                    return;
                }
                else if (map[nx][ny] != 0) {
                    cout << "Robot " << store[i].num << " crashes into robot " << map[nx][ny] << endl;
                    return;
                }
                else if (nx >= 0 && ny >= 0 && nx < B && ny < A) {
                    map[x][y] = 0;
                    robot[store[i].num].x = nx;
                    robot[store[i].num].y = ny;
                    map[nx][ny] = store[i].num;
                }
            }
            else if (store[i].com == 'L') {
                dir = robot[store[i].num].dir;
                robot[store[i].num].dir = (dir + 3) % 4;
            }
            else if (store[i].com == 'R') {
                dir = robot[store[i].num].dir;
                robot[store[i].num].dir = (dir + 1) % 4;
            }
        }
    }
 
    cout << "OK" << endl;
}
 
int main() {
    problemIn();
    solve();
    return 0;
}
cs