로봇 청소기

시뮬레이션 문제.

문제 조건 중에 바라보는 방향을 유지한 채로 한 칸 후진에 대해 바라보는 방향을 잘못 이해해서 헤맨 문제다.

바라보는 방향을 위치 이동시 바라보는 방향인데, 나는 네 바퀴 다돌리고 나서 마지막 바라보는 방향으로 설정했다.

바라보는 방향, 바라보는 방향 -1 , 바라보는 방향 -2 , 바라보는 방향 -3

이렇게 되서 바라보는 방향 -3 방향이 재귀함수에 인자로 전달되서 틀린 문제.

#include <iostream>

using namespace std;

bool cleanPaths[50][50];
int cleanCnt;
int paths[50][50];
int n,m; // 지도 크기

int dirPaths[4][2] = {
    {-1,0},
    {0,1},
    {1,0},
    {0,-1}
};

int reverseDir[4] = {2, 3, 0, 1};

/**
 * l_dir : 현재 바라보는 위치,
 * r     : row
 * c     : col
 */
void cleanUp(int l_dir, int r, int c) {
    // base case : 현재 path가 벽이라면 진입 불가. 즉시 종료.
    if(paths[r][c] == 1) return;

    // r_dir로 네 방향 탐색하기 위해 현재 바라보는 위치 할당.
    int r_dir = l_dir;

    // 청소 안되있다면, 청소 하기
    if(!cleanPaths[r][c]) {
        cleanPaths[r][c] = true;
        cleanCnt += 1;
    }

    // 네 방향 청소 여부 탐색 후, 청소하기
    for(int i = 0; i<4; i++) {
        r_dir = r_dir - 1;
        if(r_dir < 0) {
            r_dir = 3;
        }
        int nextRow = r + dirPaths[r_dir][0];
        int nextCol = c + dirPaths[r_dir][1];

        // 
        if(paths[nextRow][nextCol] == 0 && !cleanPaths[nextRow][nextCol]) {
            cleanUp(r_dir, nextRow, nextCol);
            return; 
        }
    }

    // 네 방향 모두 탐색 후에 갈 곳이 없다면 후진.
    int reverse_dir = reverseDir[l_dir];

    int reverse_row = r + dirPaths[reverse_dir][0];
    int reverse_col = c + dirPaths[reverse_dir][1];

    if(paths[reverse_row][reverse_col] == 1) {
        return;
    }
    cleanUp(l_dir, reverse_row, reverse_col);

}

int main(int argc, const char * argv[]) {


    int r,c,d; // 청소기 현재 좌표, 바라보는 방향

    cin>>n>>m;
    cin>>r>>c>>d;

    for(int i = 0; i<n; i++) {
        for(int j = 0; j<m; j++) {
            cin>>paths[i][j];
        }
    }

    cleanUp(d, r, c);

    cout<<cleanCnt<<endl;

    return 0;
}

Last updated

Was this helpful?