728x90
https://school.programmers.co.kr/learn/courses/30/lessons/87946
[ํด๊ฒฐ์ฑ ]
1) ๋์ ๊ฐ์๊ฐ ์ต๋ 8๊ฐ๋ผ์ permutation์ผ๋ก ์์ ์กฐํฉ ๋ฝ๊ณ ํ์ํ๋ฉฐ ์ต๋ ํํ ๊ฐ์๋ฅผ ๊ตฌํ๋ฉด ๋๋ค.
2) permutation๋ง๊ณ ๋ DFS๋ก๋ ํ ์ ์๋ค.
[์์๋ ๊ฒ]
* DFS/BFS Algorithm ๋ฐ ๊ตฌํ๋ฒ
* C#์ foreach๋ฌธ ๊ฐ์ for๋ฌธ ์ฌ์ฉ๋ฒ
vector<int> v = {1,2,3};
for(const auto& vValue: v){
cout << vValue; // 1, 2, 3
}
[์ฝ๋]
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(int k, vector<vector<int>> dungeons) {
int answer = -1;
//1. ์กฐํฉ ๋๋ฆฌ๊ธฐ ์ฝ๊ฒ ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
sort(dungeons.begin(), dungeons.end());
//2. ์กฐํฉ ์์๋๋ก ํ์ํ๋ฉฐ ์ต๋ ๋์ ํ์ ๊ฐ๋ฅ ์ ๊ตฌํ๊ธฐ.
do{
int count = 0;
int currentEnergy = k;
for(const auto& dungeon: dungeons){
int minEnergy = dungeon[0];
int useEnergy = dungeon[1];
if(minEnergy <= currentEnergy){
currentEnergy -= useEnergy;
count++;
}
else break;
}
answer = max(count, answer);
}while(next_permutation(dungeons.begin(), dungeons.end()));
return answer;
}
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool isVisited[8] = {false, };
int answer;
void DFS(int currentEnergy, int count, vector<vector<int>> dungeons){
//ํ์ฌ Energy๊ฐ 0 ์ดํ๋ฉด ๋ฐ๋ก returnํด์ ์๊ฐ์ค์ด๊ธฐ
if(currentEnergy <= 0){
return;
}
for(int i = 0; i < dungeons.size(); i++){
int minEnergy = dungeons[i][0];
int useEnergy = dungeons[i][1];
if(!isVisited[i] && currentEnergy >= minEnergy){
//ํด๋น ๊ฐ์ง์์ ๋์ด์ ํ์์ ์ํ๊ธฐ ์ํด ๋ฐฉ๋ฌธ true ์ฒ๋ฆฌ
isVisited[i] = true;
//๋ค์ ๊น์ด๋ก DFS ํ์
DFS(currentEnergy-useEnergy, count+1, dungeons);
//๋ฆฌํด์ ์ฌํ์์ ์ํด ๋ฐฉ๋ฌธ false์ฒ๋ฆฌ
isVisited[i] = false;
}
}
answer = max(answer, count);
}
int solution(int currentEnergy, vector<vector<int>> dungeons) {
//ํ์ฌ ์๋์ง ๊ฐ๊ณผ ํ์ ๊น์ด ๊ฐ, dungeons ๋ฒกํฐ๋ฅผ ๋๊น
DFS(currentEnergy, 0, dungeons);
return answer;
}
728x90
'๐ Coding Test Study > Algorithm Problem' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++][Programmers][DFS/BFS] ๊ฒ์ ๋งต ์ต๋จ๊ฑฐ๋ฆฌ (0) | 2023.05.04 |
---|---|
[C++][Programmers][DFS/BFS] ํ๊ฒ๋๋ฒ (0) | 2023.05.02 |
[C++][Programmers][์์ ํ์] ์นดํซ (0) | 2023.04.24 |
[C++][Programmers][์์ ํ์] ๋ชจ์๊ณ ์ฌ (0) | 2023.04.21 |
[C++][Programmers][์์ ํ์] ์ต์์ง์ฌ๊ฐํ (0) | 2023.04.21 |