Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

charminseok

[삼성 swea] 1949. 등산로 조성 본문

알고리즘/알고리즘 문제

[삼성 swea] 1949. 등산로 조성

charminseok 2019. 9. 11. 18:10

등산로 조성을 위해 2차 배열에 산의 높이가 들어가 있다. 가장 높은 곳에서 시작하고, 무조건 작은 곳으로만 등산로를 조성할 수 있다. 그리고 딱 한번 k 만큼 산을 깍을 수 있다.

 이번 문제를 풀기위해서 DFS를 사용했다. 현재 위치보다 작으면 재귀함수로 다시 실행하고, 만약 산을 깍지 않았고 다음 위치에서 k를 뺐을때 현재 위치보다 작으면 산을 깍고 재귀함수로 실행한다.

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
#include<iostream>
#include<vector>
using namespace std;
 
vector<vector<int>> map;
vector<vector<bool>> visit;
int n, k;
int dxy[4][2= { {0,1},{0,-1},{1,0},{-1,0} };
int ans;
void dfs(int a, int b, int h, int cnt, bool cut) {
    ans = ans < cnt ? cnt : ans;
 
    for (int i = 0; i < 4; i++) {
        int x = a + dxy[i][0];
        int y = b + dxy[i][1];
        int nh;
 
        if (x < 0 || x >= n || y < 0 || y >= n)
            continue;
 
        if (map[x][y] < h && !visit[x][y]) {
            visit[x][y] = true;
            dfs(x, y, map[x][y], cnt + 1, cut);
            visit[x][y] = false;
 
        }
        else if (map[x][y] >= h && !visit[x][y] && cut == false) {
            if (map[x][y] - k < h) {
                visit[x][y] = true;
                nh = h - 1;
 
                dfs(x, y, nh, cnt + 1true);
                visit[x][y] = false;
            }
        }
    }
}
int main() {
    ios_base::sync_with_stdio(NULL);
    cin.tie(NULL);
    cout.tie(NULL);
 
    int T;
    cin >> T;
    for (int t = 1; t <= T; t++) {
        cin >> n >> k;
        int high = 0;
        ans = 0;
        map.assign(n, vector<int>(n, 0));
        visit.assign(n, vector<bool>(n, false));
 
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cin >> map[i][j];
                high = high < map[i][j] ? map[i][j] : high;
            }
        }
 
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (map[i][j] == high) {
                    visit[i][j] = true;
                    dfs(i, j, high, 1false);
                    visit[i][j] = false;
                }
            }
        }
 
        cout << "#" << t << " " << ans << endl;
    }
 
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter