300x250
1. 제목
- 백준 2174 로봇 시뮬레이션
- BOJ 2174 로봇 시뮬레이션
문제 링크 : 2174번: 로봇 시뮬레이션 (acmicpc.net)
2174번: 로봇 시뮬레이션
첫째 줄에 두 정수 A, B가 주어진다. 다음 줄에는 두 정수 N, M이 주어진다. 다음 N개의 줄에는 각 로봇의 초기 위치(x, y좌표 순) 및 방향이 주어진다. 다음 M개의 줄에는 각 명령이 명령을 내리는 순
www.acmicpc.net
2. 풀이 과정
로봇이 여러 개가 있을 수 있고 이 로봇들에게 회전 또는 전진 명령을 내릴 수 있어요. 이때 이 로봇들에게 전진 명령을 내릴 때 맵밖을 벗어나는 것은 맵에 사이즈를 벗어나는지만 체크해주면 될 것이고 나머지는 다른 로봇과의 충돌인데 이걸 저는 맵에 int형 2차원 배열로 표현해서 0은 빈칸 나머지는 각 로봇에 index를 표시해 주는 방법을 사용하여서 현재 명령을 내리고 있는 로봇이 이동할 좌표에 0이 아닌 값이 있다면 해당 index 로봇과 충돌했다는 것으로 문제에서 요구하는 조건을 수행할 수 있었어요.
3. 코드
#include <iostream>
#include <vector>
#define X first
#define Y second
using namespace std;
struct Robot
{
int x;
int y;
int dir;
};
struct Command
{
int index;
char type;
int count;
};
Robot robots[101];
Command commands[101];
int map[101][101];
int w, h;
int N, M;
// 위 오른쪽 아래 왼쪽
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
void Solution()
{
for (int i = 0; i < M; i++)
{
// 회전, 전진명령 구분
char commandType = commands[i].type;
// 해당 명령을 몇번 수행할 것인지
int count = commands[i].count;
// 명령을 내릴 로봇 index
int index = commands[i].index;
for (int j = 0; j < count; j++)
{
if (commandType == 'L')
robots[index].dir = (robots[index].dir + 3) % 4;
else if (commandType == 'R')
robots[index].dir = (robots[index].dir + 1) % 4;
else if(commandType == 'F')
{
int nx = robots[index].x + dx[robots[index].dir];
int ny = robots[index].y + dy[robots[index].dir];
map[robots[index].x][robots[index].y] = 0;
// 이동할 좌표가 맵을 벗어난다면
if (nx == 0 || ny == 0 || nx > w || ny > h)
{
cout << "Robot " << index << " crashes into the wall";
return;
}
// 이동할 좌표가 빈공간이 아니라면
if (map[nx][ny] != 0)
{
cout << "Robot " << index << " crashes into robot " << map[nx][ny];
return;
}
robots[index].x = nx;
robots[index].y = ny;
map[nx][ny] = index;
}
}
}
// 정상수행 완료
cout << "OK" << endl;
}
void Input()
{
cin >> w >> h;
cin >> N >> M;
for (int i = 1; i <= N; i++)
{
int x, y, dir = 0;
char cdir;
cin >> x >> y >> cdir;
if (cdir == 'N')
dir = 0;
else if (cdir == 'E')
dir = 1;
else if (cdir == 'S')
dir = 2;
else if (cdir == 'W')
dir = 3;
robots[i] = { x, y, dir };
map[x][y] = i;
}
for (int i = 0; i < M; i++)
{
int index, count;
char type;
cin >> index >> type >> count;
commands[i] = { index, type, count };
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
Input();
Solution();
return 0;
}
300x250
'<C++ 백준 BOJ> > 구현' 카테고리의 다른 글
[백준 BOJ18111] 마인크래프트 (C++) (0) | 2022.12.27 |
---|---|
[백준 BOJ14891] 톱니바퀴 (C++) (0) | 2022.12.27 |
[백준 BOJ14719] 빗물 (C++) (0) | 2022.12.25 |
[백준 BOJ16918] 봄버맨 (C++) (2) | 2022.12.24 |
[백준 BOJ3190] 뱀 (C++) (0) | 2022.12.24 |