https://www.acmicpc.net/problem/14503
문제
입력
출력
코드
#include <iostream>
#include <vector>
using namespace std;
int N, M;
vector<vector<int>> room;
vector<vector<bool>> cleaned;
int directions[4][2] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; // 북, 동, 남, 서
int turnLeft(int d) {
return (d + 3) % 4;
}
int simulate(int r, int c, int d) {
int cleanedCount = 0;
while (true) {
if (!cleaned[r][c]) {
cleaned[r][c] = true;
cleanedCount++;
}
bool canMove = false;
for (int i = 0; i < 4; i++) {
d = turnLeft(d);
int nr = r + directions[d][0];
int nc = c + directions[d][1];
if (nr >= 0 && nr < N && nc >= 0 && nc < M && room[nr][nc] == 0 && !cleaned[nr][nc]) {
r = nr;
c = nc;
canMove = true;
break;
}
}
if (canMove) {
continue;
} else {
int backD = (d + 2) % 4;
int nr = r + directions[backD][0];
int nc = c + directions[backD][1];
if (nr >= 0 && nr < N && nc >= 0 && nc < M && room[nr][nc] == 0) {
r = nr;
c = nc;
} else {
break;
}
}
}
return cleanedCount;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> N >> M;
room.resize(N, vector<int>(M));
cleaned.resize(N, vector<bool>(M, false));
int startR, startC, startD;
cin >> startR >> startC >> startD;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
cin >> room[i][j];
}
}
int result = simulate(startR, startC, startD);
cout << result << endl;
return 0;
}
풀이
1. simulate 함수는 로봇 청소기가 청소를 진행하는 함수입니다.
2. 로봇 청소기가 청소할 수 있는 칸이 있으면 그 칸을 청소하고 이동합니다.
3. 로봇 청소기는 왼쪽으로 90도 회전하면서 빈 칸을 찾습니다. (turnLerf함수)
4. 만약 빈 칸이 있으면 그 방향으로 이동합니다. 그렇지 않으면 후진할 수 있는지 확인합니다.
5. 후진할 수 있으면 후진하고, 후진할 수 없으면 시뮬레이션을 종료합니다.