https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PoOKKAPIDFAUq
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
const int MAX = 9;
int map[MAX][MAX];
int n, K;
struct MOVE { int x, y; };
MOVE mv[4] = { {-1,0}, {1,0}, {0,-1}, {0,1} };
int visited[MAX][MAX];
int answer;
void dfs(int ii, int jj, int flag, int count) {
int tmp[MAX][MAX];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
tmp[i][j] = visited[i][j];
}
}
bool check = false;
visited[ii][jj] = 1;
for (int k = 0; k < 4; k++) {
int movei = ii + mv[k].x;
int movej = jj + mv[k].y;
if (!(movei >= 0 && movei < n && movej >= 0 && movej < n)) continue;
if (visited[movei][movej] == 1) continue;
if (map[ii][jj] <= map[movei][movej] && flag == 0) {
int tmp = map[movei][movej];
if (map[movei][movej] - map[ii][jj] + 1 <= K) {
map[movei][movej] = map[ii][jj] - 1;
if (map[ii][jj] > map[movei][movej]) {
visited[movei][movej] = 1;
dfs(movei, movej, 1, count + 1);
check = true;
}
map[movei][movej] = tmp;
visited[movei][movej] = -1;
}
}
else if(map[ii][jj] > map[movei][movej]){
visited[movei][movej] = 1;
dfs(movei, movej, flag, count + 1);
visited[movei][movej] = -1;
check = true;
}
}
if (check == false) {
answer = max(answer, count);
}
else {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
visited[i][j] = tmp[i][j];
}
}
}
}
int main(void) {
int testcase;
cin >> testcase;
int index = 1;
for (; testcase > 0; testcase--) {
answer=0;
int max_value = -1;
vector<pair<int, int>> loc;
cin >> n >> K;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> map[i][j];
if (max_value < map[i][j]) {
max_value = map[i][j];
loc.clear();
loc.push_back(make_pair(i, j));
}
else if(max_value == map[i][j]){
loc.push_back(make_pair(i, j));
}
}
}
for (int i = 0; i < loc.size(); i++) {
memset(visited, -1, sizeof(visited));
dfs(loc[i].first, loc[i].second, 0, 1);
}
cout << "#" << index << " " << answer << "\n";
index++;
}
}
'백준 알고리즘 > 구현' 카테고리의 다른 글
원자 소멸 시뮬레이션 C++ (0) | 2022.04.29 |
---|---|
탈주범 검거 C++ (0) | 2022.04.28 |
점심 식사시간 C++ (0) | 2022.04.25 |
미생물 격리 C++ (0) | 2022.04.25 |
무선 충전 C++ (0) | 2022.04.25 |