[백준 2174번] 로봇 시뮬레이션

2017. 9. 30. 00:01알고리즘/백준

반응형








소스코드


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
#include <iostream>
using namespace std;
 
char Rotate[4= { 'N''E''S''W' };
int dirX[4= {1,0,-1,0};
int dirY[4= {0,1,0,-1};
 
struct robot{
    int x;
    int y;
    int rot;
};
int a,b,n,m,map[102][102];
robot rb[102];
 
void L(int id, int cnt) {
    int tmpVal = rb[id].rot - (cnt % 4);
    rb[id].rot = tmpVal < 0 ? tmpVal+4 : tmpVal;
}
void R(int id, int cnt) {
    int tmpVal = rb[id].rot + (cnt % 4);
    rb[id].rot = tmpVal > 3 ? tmpVal - 4 : tmpVal;
}
int F(int id, int cnt) {  // ret   0 = success, 1 = crash wall, 1000<=val = crash robot (val/1000 crash val%0100)
    for (int i = 0; i < cnt; i++) {
        int CurX = rb[id].x;
        int CurY = rb[id].y;
        int tmpValX = rb[id].x + dirX[rb[id].rot];
        int tmpValY = rb[id].y + dirY[rb[id].rot];
        int pos = map[tmpValX][tmpValY];
        if (tmpValX <= b && tmpValX >= 1 && tmpValY >= 1 && tmpValY <= a) {
            if (pos==0) {
                map[CurX][CurY] = 0;
                map[tmpValX][tmpValY] = id;
                rb[id].x = tmpValX, rb[id].y = tmpValY;
            }
            else
                return id * 1000 + pos;
        }
        else // Out of Range
            return 1;
    }
    return 0;
}
int binding(char command) {
    for (int i = 0; i < 4; i++)
        if (Rotate[i] == command)
            return i;
}
int main() {
    cin >> a >> b >> n >> m;
    for (int i = 1; i <= n; i++) {
        int x, y;
        char rotTmp;
        cin >> y >> x >> rotTmp;
        rb[i].x = x;
        rb[i].y = y;
        rb[i].rot = binding(rotTmp);
        map[x][y] = i;
    }
    //명령
    for (int i = 0; i < m; i++) {
        int id, cnt;
        char command;
        cin >> id >> command >> cnt;
        if (command == 'L') {
            L(id, cnt);
        }
        else if (command == 'R') {
            R(id, cnt);
        }
        else if (command == 'F') {
            int ret = F(id, cnt);
            if (ret == 1) {
                cout << "Robot " << id << " crashes into the wall" << '\n';
                return 0;
            }
            else if (ret > 1000) {
                cout << "Robot " << ret/1000 << " crashes into robot " << ret%1000 << '\n';
                return 0;
            }
        }
    }
    cout << "OK" << '\n';
    return 0;
}
cs


반응형