📕알고리즘 문제/📝Baekjoon
[백준] 골드5 : (14503) 로봇 청소기
주으기
2024. 12. 5. 13:51
728x90
반응형
https://www.acmicpc.net/problem/14503
간단한 시뮬레이션 유형의 구현 문제이다.
문제의 설명 그대로 구현하면 풀린다.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int dy[]{ -1, 0, 1, 0 };
int dx[]{ 0, 1, 0, -1 };
int N, M, Dir, Answer = 0;
// 형재 청소기 위치
pair<int, int> Pos;
cin >> N >> M;
cin >> Pos.first >> Pos.second >> Dir;
vector<vector<int>> Room(N, vector<int>(M, 0));
for (int y = 0; y < N; ++y)
for (int x = 0; x < M; ++x)
cin >> Room[y][x];
while (true)
{
int y = Pos.first, x = Pos.second;
// 현재 칸이 아직 청소되지 않은 경우, 현재 칸을 청소한다.
if (Room[y][x] == 0) Room[y][x] = 2, Answer++;
else
{
// 현재 칸의 주변 4칸 중, 청소되지 않은 빈 칸이 있는지 검사한다.
bool Check = false;
for (int i = 0; i < 4; ++i)
{
int ny = y + dy[i], nx = x + dx[i];
if (ny < 0 || nx < 0 || ny >= N || nx >= M || Room[ny][nx] != 0) continue;
Check = true;
break;
}
// 빈 칸이 있는 경우
if (Check)
{
// 반시계 방향으로 90도 회전
Dir == 0 ? Dir = 3 : Dir--;
// 바라보는 방향을 기준으로 앞쪽 칸이 청소되지 않은 빈 칸인 경우 한 칸 전진한다.
if (Room[y + dy[Dir]][x + dx[Dir]] == 0) y += dy[Dir], x += dx[Dir];
}
// 빈 칸이 없는 경우
else
{
// 바라보는 방향의 뒤쪽 칸이 벽이라 후진할 수 없다면 작동을 멈춘다.
if (Room[y - dy[Dir]][x - dx[Dir]] == 1) break;
y -= dy[Dir], x -= dx[Dir];
}
Pos.first = y, Pos.second = x;
}
}
cout << Answer << "\n";
}
728x90
반응형