[백준 1600번] 말이 되고픈 원숭이

2017. 10. 12. 00:08알고리즘/백준

반응형





소스코드


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
#include <iostream>
using namespace std;
 
struct position {
    int x;
    int y;
    int cnt;
};
 
int k, w, h, map[215][215],v[35][215][215],chk[215][215];
int mdx[4= { 00-11 };
int mdy[4= { -1100 };
int hdx[8= {-1,-2,-2,-1,1,2,2,1};
int hdy[8= {-2,-1,1,2,2,1,-1,-2};
position pos[1500000];
int head, tail;
 
void bfs() {
    while (head != tail) {
        int curX = pos[head].x;
        int curY = pos[head].y;
        int curCnt = pos[head].cnt;
 
        if (curX == h - 1 && curY == w - 1) {
            cout << chk[curX][curY] << '\n';
            return;
        }
 
        for (int i = 0; i < 4; i++) {
            int xx = curX + mdx[i];
            int yy = curY + mdy[i];
            if (xx < 0 || xx >= h || yy < 0 || yy >= w) { continue; }
            if (!map[xx][yy] && !v[curCnt][xx][yy]) {
                v[curCnt][xx][yy] = 1;
                pos[tail].x = xx;
                pos[tail].y = yy;
                pos[tail].cnt = curCnt;
                chk[xx][yy] = chk[curX][curY] + 1;
                tail++;
            }
        }
 
        if (curCnt>0) {
            for (int i = 0; i < 8; i++) {
                int xx = curX + hdx[i];
                int yy = curY + hdy[i];
                if (xx < 0 || xx >= h || yy < 0 || yy >= w) { continue; }
                if (!map[xx][yy] && !v[curCnt-1][xx][yy]) {
                    v[curCnt-1][xx][yy] = 1;
                    pos[tail].x = xx;
                    pos[tail].y = yy;
                    pos[tail].cnt = curCnt - 1;
                    chk[xx][yy] = chk[curX][curY] + 1;
                    tail++;
                }
            }
        }
 
        head++;
    }
    cout << -1 << '\n';
}
 
 
 
int main() {
    cin >> k >> w >> h;
    for (int i = 0; i < h; i++)
        for (int j = 0; j < w; j++)
            cin >> map[i][j];
    pos[0].x = 0, pos[0].y = 0, pos[0].cnt = k;
    v[k][0][0= 1;
    head = 0, tail = 1;
    bfs();
    return 0;
}
cs


반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 1405번] 미친 로봇  (0) 2017.10.16
[백준 3085번] 사탕 게임  (0) 2017.10.12
[백준 1451번] 직사각형으로 나누기  (0) 2017.10.11
[백준 1331번] 나이트 투어  (0) 2017.10.08
[백준 3980번] 선발 명단  (0) 2017.10.06