Little Jay

[C++] 백준 2174 - 로봇 시뮬레이션 본문

알고리즘/BOJ

[C++] 백준 2174 - 로봇 시뮬레이션

Jay, Lee 2022. 7. 19. 16:59

빡구현 문제이다.

여기서 어려웠던 부분은 명령어 별로 벽에 부딪혔을 때 나머지 명령어도 받아야 하는 부분의 처리가 좀 까다로웠다. 

구조체를 활용하여 위 부분만 조심하면 크게 어렵지는 않았던 문제였던 것 같다.

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;

int a, b;
int n, m;
int num, orders;
char action;

struct rb {
	int x;
	int y;
	char direction;
};

rb robots[101];

bool checkWall(int num) {
	if (robots[num].x <= 0 || robots[num].y <= 0 || robots[num].x > a || robots[num].y > b) {
		cout << "Robot " << num << " crashes into the wall" << endl;
		return true;
	}
	return false;
}

bool checkCrash(int num) {
	for (int i = 1; i <= n; i++) {
		if (num != i && robots[num].x == robots[i].x && robots[num].y == robots[i].y) {
			cout << "Robot " << num << " crashes into robot " << i << endl;
			return true;
		}
	}
	return false;
}

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	cin >> a >> b;
	cin >> n >> m;

	for (int i = 1; i <= n; i++) {
		int x, y; char dir; cin >> x >> y >> dir;
		robots[i].x = x;
		robots[i].y = y;
		robots[i].direction = dir;
	}

	for (int i = 0; i < m; i++) {
		cin >> num >> action >> orders;
		if (action == 'L' || action == 'R') orders %= 4;

		for (int cnt = 0; cnt < orders; cnt++) {
			if (action == 'F') {
				int dx = 0, dy = 0;
				switch (robots[num].direction) {
				case 'N':
					dy += 1;
					break;
				case 'S':
					dy -= 1;
					break;
				case 'W':
					dx -= 1;
					break;
				case 'E':
					dx += 1;
					break;
				}
				robots[num].x += dx;
				robots[num].y += dy;
				if (checkWall(num) == true) {
					cnt++;
					for (++cnt; cnt < m; cnt++) {
						cin >> num >> action >> orders;
					}
					return 0;
				}
				if (checkCrash(num) == true) {
					cnt++;
					for (++cnt; cnt < m; cnt++) {
						cin >> num >> action >> orders;
					}
					return 0;
				}
			}
			else if (action == 'L') {
				switch (robots[num].direction) {
				case 'N':
					robots[num].direction = 'W';
					break;
				case 'S':
					robots[num].direction = 'E';
					break;
				case 'W':
					robots[num].direction = 'S';
					break;
				case 'E':
					robots[num].direction = 'N';
					break;
				}
			}
			else if (action == 'R') {
				switch (robots[num].direction) {
				case 'N':
					robots[num].direction = 'E';
					break;
				case 'S':
					robots[num].direction = 'W';
					break;
				case 'W':
					robots[num].direction = 'N';
					break;
				case 'E':
					robots[num].direction = 'S';
					break;
				}
			}
		}
	}
	cout << "OK" << endl;

	return 0;
}
Comments