Post List

[BOJ] 백준 1937 욕심쟁이 판다

문제 링크 : https://www.acmicpc.net/problem/1937

이 문제는 이전에 갔던 곳 이라면, 그 곳엔 적당한 값이 저장되어있으므로 한번 더 가보지 않고 값만 받아오는, 즉 dp를 사용하는 문제 입니다.

이전에 비슷한 문제를 풀어보았는데요 백준 1890 점프 입니다.
'점프' 문제에선 오른쪽, 아래쪽만 갔었는데요, 이 판다는 4방향 전부 가고 특정한 목적지가 없습니다. 갈 수 있는 곳 까지만 가봅니다.

방식은 이렇습니다.

이차원 배열상 한 셀에서 이동할 수 있는 모든 지점을 받습니다.
이것을 n x n 번 반복합니다.

그 후, n x n 행렬중에서 가장 큰 값을 얻습니다.

소스코드 :

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
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <stack>
#include <string>
#include <cmath>
#include <map>
#include <cstdlib>
#include <ctime>
#include <map>
using namespace std;
vector<vector<int> > dp(501vector<int>(501));
int n;
int dy[4= { 1,-1,0,0 };
int dx[4= { 0,0,1,-1 };
int Maximum(vector<int> variable) {
    sort(variable.begin(), variable.end());
    return variable[variable.size() - 1];
}
int Panda(int y, int x, vector<vector<int> > & v) {
    
    if (dp[y][x] == 0) {
        vector<int> t(4);
        for (int i = 0; i < 4; i++) {
            int ty = y + dy[i];
            int tx = x + dx[i];
            if (ty <= n && ty >= 1 && tx <= n && tx >= 1) {
                if(v[ty][tx] < v[y][x])
                    t[i] = Panda(ty, tx, v);
            }
        }
        // 최대 생존기간(루트)에 본인 생존기간 1일 추가.
        dp[y][x] = Maximum(t) + 1;
    }
    return dp[y][x] ;
}
int main() {
    cin.tie(0);
    ios_base::sync_with_stdio(false);
    cin >> n;
    vector<vector<int> > v(n + 1vector<int>(n + 1));
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> v[i][j];
        }
    }
    
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (dp[i][j] == 0) {
                dp[i][j] = Panda(i, j, v);
            }
        }
    }
    
    int k = -1;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (k < dp[i][j]) {
                k = dp[i][j];
            }
        }
    }
    cout << k << endl;
}
cs

댓글