티스토리 뷰

출처 : https://www.swexpertacademy.com/main/code/problem/problemDetail.do


#include <iostream>

#include <algorithm>
using namespace std;
 
#define MAX_N 9
 
int N, K, result, max_num;
int map[MAX_N][MAX_N];
bool check[MAX_N][MAX_N], used;
int dir[4][2] = { { 1,0 },{ -1,0 },{ 0,1 },{ 0,-1 } };
 
void dfs(int i, int j, int count)
{
    for (int d = 0; d < 4; d++)
    {
        int nexti = i + dir[d][0]; int nextj = j + dir[d][1];
 
        if (nexti >= 0 && nexti <= N - 1 && nextj >= 0 && nextj <= N - 1 && !check[nexti][nextj])
        {
            if (map[i][j] > map[nexti][nextj])
            {
                check[nexti][nextj] = true;
                dfs(nexti, nextj, count + 1);
                check[nexti][nextj] = false;
            }
            else if (!used && map[i][j] > map[nexti][nextj] - K && !check[nexti][nextj])
            {
                int tmp = map[nexti][nextj];
                used = true; map[nexti][nextj] = map[i][j]-1; check[nexti][nextj] = true;
                dfs(nexti, nextj, count + 1);
                used = false; map[nexti][nextj] = tmp; check[nexti][nextj] = false;
            }
        }
 
        result = max(result, count);
    }
}
 
void cal()
{
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (map[i][j] == max_num)
            {
                check[i][j] = true;
                dfs(i, j, 1);
                check[i][j] = false;
            }
        }
    }
}
 
int main()
{
    int T; int tc = 1;
    cin >> T;
    while (T--)
    {
        cin >> N >> K; max_num = 0; result = 0; used = false;
        for (int i = 0; i < N; i++) for (int j = 0; j < N; j++)
        {
            check[i][j] = false;
            cin >> map[i][j];
            max_num = max(max_num, map[i][j]);
        }
        cal();
        cout << "#" << tc << " " << result << endl;
        tc++;
    }
 
    return 0;
}


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

[SWEA 2112] 보호 필름  (2) 2018.07.23
[SWEA 2105] 디저트 카페  (0) 2018.07.23
[SWEA 4014] 활주로 건설  (0) 2018.07.23
[SWEA 4013] 특이한 자석  (0) 2018.07.23
[SWEA 3752] 가능한 시험 점수  (0) 2018.07.23
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
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
글 보관함