본문 바로가기

BOJ

백준 1600 / 말이 되고픈 원숭이


BFS / DP 문제



BFS로 풀었다.


맵을 제외한 check와 d배열에 말짓(?) 횟수를 담을 수 있게 3차원으로 만들었다.




!!!!!!!! 문제 제대로 읽고 가로 세로 정확히 파악하자 !!!!!! 



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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include<iostream>
#include<stdio.h>
#include<vector>
#include<queue>
#include<tuple>
#include<algorithm>
 
using namespace std;
int map[201][201];
int d[201][201][31];
bool check[201][301][31];
 
queue<tuple<intintint>>q;
 
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,1,-1 };
int kx[] = { -1,-2,-2,-1,1,2,2,1 };
int ky[] = { -2,-1,1,2,2,1,-1,-2 };
 
 
int main() {
 
    //freopen("Text.txt", "r", stdin);
    int k;
 
    int n,m;
    cin >> k;
    cin >> m >> n;
 
    if (n == 1 && m == 1) {
        cout << 0;
        return 0;
    }
 
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> map[i][j];
        }
    }
 
    q.push(make_tuple(00, k));
 
    check[0][0][k] = true;
 
    while (!q.empty()) {
        int x, y, ngt;
        tie(x, y, ngt) = q.front();
        q.pop();
 
        
 
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
 
            if (nx >= 0 && ny >= 0 && nx < n && ny < m) {
                if (map[nx][ny] == 0 && check[nx][ny][ngt] == false && ngt >=0) {
                    check[nx][ny][ngt] = true;
                    d[nx][ny][ngt] = d[x][y][ngt] + 1;
                    q.push(make_tuple(nx, ny, ngt));
                }
            }
 
        }
 
        for(int i = 0; i < 8; i++) {
            int ngtx = x + kx[i];
            int ngty = y + ky[i];
 
            if (ngtx >= 0 && ngty >= 0 && ngtx < n && ngty < m) {
                if (map[ngtx][ngty] == 0 && check[ngtx][ngty][ngt-1== false && ngt>0) {
                    check[ngtx][ngty][ngt-1= true;
                    d[ngtx][ngty][ngt - 1= d[x][y][ngt] + 1;
                    q.push(make_tuple(ngtx, ngty, ngt - 1));
 
                }
            }
        }
    }
    
 
    vector<int>ans;
    int cnt = 0;
 
    for (int i = 0; i <= k; i++) {
        
        if (d[n - 1][m - 1][i] != 0) {
            cnt++;
            ans.push_back(d[n - 1][m - 1][i]);
        }
    }
 
    if (cnt == 0) {
 
        cout << -1;
 
    }
    else {
        sort(ans.begin(), ans.end());
        
        for (int i = 0; i <ans.size(); i++) {
            if (ans[i] != 0) {
                cout << ans[i];
                break;
            }
        }
 
 
    }
 
 
}
cs


'BOJ' 카테고리의 다른 글

백준 1939 / 중량제한  (0) 2019.01.09
백준 5427 / 불  (0) 2019.01.08
백준 1967 / 트리의 지름  (0) 2019.01.07
백준 2146 / 다리 만들기  (0) 2019.01.05
백준 9019 / DSLR  (0) 2019.01.05