프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이 과정
이 문제는 (0, 1, 2)(0, 2, 1)(1, 0, 2)(1, 2, 0)(2, 0, 1)(2, 1, 0)
다 돌아보면서 가장 많이 탐험할 수 있는 던전의 수를 세는 것이다.
그러므로, next_permutation 알고리즘과 dfs 알고리즘을 둘 다 쓸 수 있다.
풀이 1 (next_permutation)
next_permutation 알고리즘을 쓰기 전에 먼저 정렬을 해준다.
k의 수는 순열 돌 때마다 같은 수여야 되기 때문에 num 변수를 따로 선언해준다.
num보다 최소 필요 소모도가 작거나 같으면 탐험할 수 있다는 뜻이므로
num에 소모 피로도를 빼주며 cnt를 세준다.
최종적으로 cnt의 최대값을 찾으면 최대 던전 수가 나온다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(int k, vector<vector<int>> dungeons) {
int answer = 0;
sort(dungeons.begin(), dungeons.end());
do{
int num = k;
int cnt = 0;
for(int i = 0; i < dungeons.size(); i++){
if(dungeons[i][0] <= num){
num -= dungeons[i][1];
cnt++;
}
}
answer = max(answer, cnt);
}while(next_permutation(dungeons.begin(), dungeons.end()));
return answer;
}
풀이 2 (dfs)
dfs의 기초이다. 먼저, bool 자료형의 visited배열을 선언해준다.
방문했거나, 최소 소모 피로도보다 현재 피로도가 더 작으면 넘어가며 dfs를 실행하면 된다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int res;
bool visited[9];
int dfs(vector<vector<int>> dungeons, int k, int cnt){
res = max(res, cnt); // 최대 던전수
for(int i = 0; i < dungeons.size(); i++){
// 방문 || 최소 필요 피로도 > 현재 피로도
if (visited[i] || dungeons[i][0] > k) continue;
visited[i] = 1;
dfs(dungeons, k - dungeons[i][1], cnt + 1); // 현재 피로도 - 소모 피로도
visited[i] = 0;
}
return res;
}
int solution(int k, vector<vector<int>> dungeons) {
int answer = -1;
answer = dfs(dungeons, k, 0);
return answer;
}
'🍞 Problem Solving > Programmers' 카테고리의 다른 글
[프로그래머스][Level3] 가장 먼 노드 c++ (0) | 2022.10.21 |
---|---|
[프로그래머스][Level2] 행렬의 곱셈 c++ (0) | 2022.10.21 |
[프로그래머스][Level2] 줄 서는 방법 c++ (0) | 2022.10.21 |
[프로그래머스][Level2] 이진 변환 반복하기 c++ (0) | 2022.10.21 |
[프로그래머스][Level2] 오픈채팅방 c++ (0) | 2022.10.21 |