Posts 백준 2174 로봇 시뮬레이션 c++
Post
Cancel

백준 2174 로봇 시뮬레이션 c++

문제

https://www.acmicpc.net/problem/2174

문제해설

좌표위에 N개의 로봇들이 존재한다.
이 로봇들은 동서남북 중에 하나의 방향을 가진다.
로봇들에게 M개의 명령이 주어진다.
명령은 앞으로가는 F와
오른쪽으로 90도 방향을 트는 R과
왼쪽으로 90도 방향을 트는 L이 존재한다.

N개의 로봇이 각자 하나씩 명령을 수행하면서
벽에 부딪히거나 다른 로봇에 부딪히거나
명령이 끝날 때까지 아무일도 안일어나는지 판단하면 된다.

문제풀이

특별한 알고리즘이 있는게 아닌 구현문제이다.
이런 문제는 처음 코딩을 할 때 실수하지 않는게 중요하다.
가장 실수하기 좋은 부분은 일단 동서남북의 방향이다.
처음 시작을 잘못 잡으면 뒤로가면서 코딩이 힘들어진다.
또한 방향전환을 하면서도 실수할 가능성이 높다.
나도 방향전환 부분에서 조건문을 잘못 설정해서 한번 틀렸다.

조금 까다로운 부분이라면 각 로봇에 번호가 붙여져있고
이 번호에 해당하는 로봇을 찾아 명령을 수행해야 된다.
그래프를 전부 다 찾는건 너무 무식하다고 생각해서
벡터를 하나 만들어 벡터의 인덱스에 해당하는 로봇의 위치를 저장해주었다.

전체코드

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
#include<iostream>
#include<algorithm>
#include<vector>
#define N 1;
#define E 2;
#define S 3;
#define W 4;
using namespace std;
typedef pair<int, int>P;
int dx[] = { 0,0,1,0,-1 };
int dy[] = { 0,1,0,-1,0 };
P arr[101][101];

int main() {
	ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
	int a, b; cin >> a >> b;
	int n, m; cin >> n >> m;
	vector<P>robot(1, { 0,0 });
	for (int i = 1; i <= n; i++) {
		int x, y; char d;
		cin >> x >> y >> d;
		int dir = 0;
		if (d == 'N') dir = 1;
		else if (d == 'E') dir = 2;
		else if (d == 'S') dir = 3;
		else if (d == 'W') dir = 4;
		arr[x][y].first = i;
		arr[x][y].second = dir;
		robot.push_back({ x,y });
	}
	for (int i = 0; i < m; i++) {
		int num, cnt; char order;
		cin >> num >> order >> cnt;

		int x = robot[num].first;
		int y = robot[num].second;
		int dir = arr[x][y].second;

		if (order == 'F') {
			arr[x][y].first = 0;
			arr[x][y].second = 0;
			for (int j = 0; j < cnt; j++) {
				int nx = x + dx[dir];
				int ny = y + dy[dir];
				if (nx <= 0 || nx > a || ny <= 0 || ny > b) {
					cout << "Robot "<< num <<" crashes into the wall";
					return 0;
				}
				if (arr[nx][ny].first != 0) {
					cout << "Robot " << num << " crashes into robot " << arr[nx][ny].first;
					return 0;
				}
				x = nx; y = ny;
			}
			arr[x][y].first = num;
			arr[x][y].second = dir;
			robot[num].first = x;
			robot[num].second = y;
		}
		else if (order == 'R') {
			while (cnt--) {
				arr[x][y].second += 1;
				if (arr[x][y].second > 4)
					arr[x][y].second = 1;
			}
		}
		else if (order == 'L') {
			while (cnt--) {
				arr[x][y].second -= 1;
				if (arr[x][y].second < 1)
					arr[x][y].second = 4;
			}
		}
	}
	cout << "OK";
	return 0;
}

백준 16112 5차 전직 c++

백준 17142 연구소 3 c++

Comments powered by Disqus.