반갑습니다!

[백준] 14503 로봇 청소기 본문

알고리즘 문제 풀이

[백준] 14503 로봇 청소기

김덜덜이 2020. 5. 4. 15:12
14503번: 로봇 청소기
 
www.acmicpc.net

풀이

문제에서 주어진대로 구현하면 되는 시뮬레이션 문제이다. 로봇이 탐색하는 부분을 구현하는 것이 핵심이다.

코드

#include <iostream>
using namespace std;

int r, c, rx, ry, rd;
int map[50][50];
const int dx[] = { 0, 1, 0, -1 }, dy[] = { -1, 0, 1, 0 };

int simulation() {
    // 청소한 바닥의 개수
    int cnt = 0;
    while (true) {
        int x = rx; int y = ry;
        // 현재 위치의 바닥 청소
        if (map[y][x] == 0) {
            map[y][x] = 2;
            cnt++;
        }

        bool wash = false;
        // 현재 방향의 왼쪽 방향부터 탐색
        for (int i = 1; i <= 4; i++) {
            int d = (rd - i + 4) % 4;
            int nx = x + dx[d]; int ny = y + dy[d];
            // 청소를 안했으면 해당 방향으로 이동
            if (map[ny][nx] == 0) {
                rx = nx; ry = ny;
                rd = d;
                wash = true;
                break;
            }
        }
        // 4방향 다 청소가 불가능한 경우
        if (!wash) {
            int d = rd;
            // 뒤로 이동할 수 없는 경우 작동 중지
            if (map[y - dy[d]][x - dx[d]] == 1) break;
            rx = x - dx[d]; ry = y - dy[d];
        }
    }
    return cnt;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> r >> c;
    cin >> ry >> rx >> rd;
    for (int i = 0; i < r; i++)
        for (int j = 0; j < c; j++)
            cin >> map[i][j];
    cout << simulation() << '\n';
    return 0;
}