구현, 시뮬레이션 문제
문제를 좀 꼬아놔서 힘들었다.
먼저 문제의 지문에서 번호가 1 2 1 2 3 1 2 3 이렇게 되어있는데,
1,
2, 2-1, 2-2
3, 3-1, 3-2, 3-3
이렇게 봐야한다.
또 로봇청소기는 반시계방향(북서남동)으로 돌지만,
문제에서 주어지는 d의 방향은 시계방향(북동남서)이다.
마지막으로 로봇청소기가 북쪽으로 이동할 때, y는 -1이 된다는 것에 주의
전체코드
#include <iostream>
using namespace std;
int n, m, d;
int arr[51][51]{};
bool visited[51][51]{};
int dy[4] = { -1, 0, 1, 0 };
int dx[4] = { 0, -1, 0, 1 };
int Func(int startY, int startX) {
visited[startY][startX] = true;
int y = startY;
int x = startX;
int cnt = 1;
while (1) {
bool isClean = false;
int curdir = d;
for (int i = 0; i < 4; ++i) {
d = (d + 1) % 4;
int ny = dy[d] + y;
int nx = dx[d] + x;
if (ny < 0 || nx < 0 || ny >= n || nx >= m
|| arr[ny][nx] == 1 || visited[ny][nx])
continue;
isClean = true;
visited[ny][nx] = true;
y = ny;
x = nx;
++cnt;
break;
}
if (isClean)
continue;
int tempDir = (curdir + 2) % 4;
int ny = dy[tempDir] + y;
int nx = dx[tempDir] + x;
if (ny < 0 || nx < 0 || ny >= n || nx >= m
|| arr[ny][nx] == 1)
break;
y = ny;
x = nx;
d = curdir;
}
return cnt;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int r, c;
cin >> n >> m >> r >> c >> d;
if (d == 1) d = 3;
else if (d == 3) d = 1;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
cin >> arr[i][j];
cout << Func(r, c);
return 0;
}
https://www.acmicpc.net/problem/14503
'알고리즘 공부' 카테고리의 다른 글
백준 14499번 주사위 굴리기 C++ (0) | 2025.03.04 |
---|---|
백준 11051번 이항 계수 2 C++ (0) | 2025.02.13 |
백준 2206번 벽 부수고 이동하기 C++ (0) | 2024.12.08 |
백준 2630번 색종이 만들기 C++ (0) | 2024.11.25 |
백준 1238번 파티 C++ (0) | 2024.11.24 |