본문 바로가기
Programming/Algorithm

백준 14503 로봇 청소기

by OKOK 2018. 4. 6.

1. 주어진 조건대로 코딩을 하면 됩니다.

2. 턴과 시간에 대해서 지난번보다 더 자연스러워졌습니다.

3. 그리고 조건을 내가 스스로 정리하면 좋습니다. 지금 현재 정리되어 나와있었기 때문에 쉽게 할 수 있었습니다.

4. 그리고 한번 조건문에서 틀린것에 대해서 다음에는 틀리지 않도록 합니다. continue 문을 써야하는 곳과 아닌 곳을 확실하게 구분하도록 합니다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
1700 문제 시작합니다.
30분컷 목표로 합니다.
로봇 청소기가 청소한 칸의 개수를 출력합니다.
22분컷!
*/
 
#include <iostream>
using namespace std;
 
#define SIZE 55 // 55
int map[SIZE][SIZE];
int N, M;
int startX, startY, startDir;
int dx[] = { -1,0,1,0 }; // 북 동 남 서 
int dy[] = { 0,1,0,-1 };
int x, y, nx, ny, dir;
int clean_cnt, turn_cnt;
int index;
 
void problemIn() {
    cin >> N >> M;
    cin >> startX >> startY >> startDir;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            cin >> map[i][j];
        }
    }
}
 
void solve() {
 
    x = startX;
    y = startY;
    dir = startDir;
    clean_cnt = 1;
//    index = 2; // 확인용
 
    while (1) {
 
        map[x][y] = 2// 현재 자리를 청소합니다.
        dir = (dir - 1 + 4) % 4;
        turn_cnt++;
 
        nx = x + dx[dir];
        ny = y + dy[dir];
        
        if (nx >= 0 && ny >= 0 && nx < N && ny < M) { // 맵 안에 들면서,
            if (map[nx][ny] == 0) { // 청소할 공간이 있다면,
                clean_cnt++;
                x = nx;
                y = ny;
                turn_cnt = 0;
                continue;
            }
            else if (map[nx][ny] != 0) { // 청소할 공간이 없다면,
                // 4바퀴를 돌았다면, 후진
                if (turn_cnt >= 4) {
                    if (dir == 0) {
                        nx = x + dx[2];
                        ny = y + dy[2];
                    }
                    else if (dir == 1) {
                        nx = x + dx[3];
                        ny = y + dy[3];
                    }
                    else if (dir == 2) {
                        nx = x + dx[0];
                        ny = y + dy[0];
                    }
                    else {
                        nx = x + dx[1];
                        ny = y + dy[1];
                    }
 
                    // 후진을 할 곳이 벽이거나, 맵 바깥이면, 중단
                    if (nx < 0 || ny < 0 || nx >= N || ny >= M || map[nx][ny] == 1) {
                        break;
                    }
                    else { // 후진 할 수 있으면, 합니다.
                        x = nx;
                        y = ny;
                        turn_cnt = 0// turn 횟수도 리셋해줍니다.
                    }
                }
            }
        }
    }
}
 
int main() {
    problemIn();
    solve();
    cout << clean_cnt << endl;
    return 0;
}
cs