1일1알

백준 2174번 로봇 시뮬레이션 C++ 본문

알고리즘

백준 2174번 로봇 시뮬레이션 C++

영춘권의달인 2022. 3. 20. 12:33

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

 

x,y좌표를 2차원 배열의 row, col 좌표로 변환한 뒤 시뮬레이션으로 문제를 해결하였다.

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>

using namespace std;
using ll = long long;

int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };

struct Robot {
	int num;
	int row;
	int col;
	int dir;
};

struct Order {
	int num;
	char _order;
	int cnt;
};

pair<int, int> Convert(int x, int y, int b) {
	x--;
	y--;
	y = b - 1 - y;
	return { y,x };
}

int MoveRobot(Robot &robot, char order, vector<vector<int>> &board, int r, int c) {
	// 벽에 박으면 -1
	// 움직일 수 있으면 0
	// 다른 로봇이랑 박으면 다른 로봇의 번호 반환

	if (order == 'L') {
		robot.dir = (robot.dir + 3) % 4;
		return 0;
	}
	if (order == 'R') {
		robot.dir = (robot.dir + 1) % 4;
		return 0;
	}
	int nextRow = robot.row + dRow[robot.dir];
	int nextCol = robot.col + dCol[robot.dir];
	if (nextRow < 0 || nextRow >= r) return -1;
	if (nextCol < 0 || nextCol >= c) return -1;
	if (board[nextRow][nextCol] != -1) return board[nextRow][nextCol];
	board[robot.row][robot.col] = -1;
	board[nextRow][nextCol] = robot.num;
	robot.row = nextRow;
	robot.col = nextCol;
	return 0;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int a, b;
	cin >> a >> b;
	vector<vector<int>> board(b, vector<int>(a, -1));
	int n, m;
	cin >> n >> m;
	vector<Robot> robots(n + 1);
	vector<Order> orders(m);
	for (int i = 1; i <= n; i++) {
		int x, y, dir;
		char d;
		cin >> x >> y >> d;
		pair<int, int> pos = Convert(x, y, b);
		//cout << pos.first << " " << pos.second << "\n";
		if (d == 'N') dir = 0;
		else if (d == 'E') dir = 1;
		else if (d == 'S') dir = 2;
		else if (d == 'W') dir = 3;
		robots[i] = { i,pos.first,pos.second,dir };
		board[pos.first][pos.second] = i;
	}
	for (int i = 0; i < m; i++) {
		int num, cnt;
		char _order;
		cin >> num >> _order >> cnt;
		orders[i] = { num,_order,cnt };
	}
	int currOrder = 0;
	bool isPossible = true;
	while (true) {
		if (orders[currOrder].cnt == 0) currOrder++;
		if (currOrder >= m) break;
		int res = MoveRobot(robots[orders[currOrder].num], orders[currOrder]._order, board, b, a);
		orders[currOrder].cnt--;
		if (res == 0) continue;
		if (res == -1) {
			cout << "Robot " << orders[currOrder].num << " crashes into the wall";
			isPossible = false;
			break;
		}
		cout << "Robot " << orders[currOrder].num << " crashes into robot " << res;
		isPossible = false;
		break;
	}
	if (isPossible) cout << "OK";
};

'알고리즘' 카테고리의 다른 글

백준 1475번 방 번호 C++  (0) 2022.03.23
백준 6198번 옥상 정원 꾸미기 C++  (0) 2022.03.21
백준 2688번 줄어들지 않아 C++  (0) 2022.03.19
백준 12904번 A와 B C++  (0) 2022.03.18
백준 1405번 미친 로봇 C++  (0) 2022.03.17