https://school.programmers.co.kr/learn/courses/30/lessons/92343
ํ๋ก๊ทธ๋๋จธ์ค
SW๊ฐ๋ฐ์๋ฅผ ์ํ ํ๊ฐ, ๊ต์ก, ์ฑ์ฉ๊น์ง Total Solution์ ์ ๊ณตํ๋ ๊ฐ๋ฐ์ ์ฑ์ฅ์ ์ํ ๋ฒ ์ด์ค์บ ํ
programmers.co.kr
ํ๋ก๊ทธ๋๋จธ์ค ๋ ๋ฒจ 3.
๊ฝค๋ ๊น๋ค๋ก์ ๋ ๋ฌธ์ ๐ฟ
ํ์ ์ ์กฐ๊ฑด์ด ์์ผ๋ฏ๋ก, dfs ๋ฐฑํธ๋ํน์ ์ ์ฉํ๋ค.
๊ทผ๋ฐ ๋ฐฑํธ๋ํน์.. ์ํด๋ ๋๋ค (๋จ๋ฐฉํฅ ๊ทธ๋ํ์ด๊ณ , ๋ฐฉ๋ฌธ ์ฒดํฌ๊ฐ ์์)
DFS์ ํ์ฌ ์ธ๋ฑ์ค, ์์ ์, ๋๋์ ์, ๊ทธ๋ฆฌ๊ณ ํ์ฌ ์์น์์ ๊ฐ ์ ์๋ ๋ค์ ๋ ธ๋ ๋ชฉ๋ก์ ์ ๋ฌํ๋ฉด
์ฐ๊ฒฐ๋ ๋ค์ ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๊ณ
์กฐ๊ฑด์ ๋ง์ง ์์ผ๋ฉด ์ฌ๊ท๋ฅผ ์ค๋จํ๊ณ ๋ฐํํ๋ค.
bfs๋ก ํธ๋ ๋ฐฉ๋ฒ๋ ์๋๋ฐ, ๊ทธ๊ฑด ์๋์ ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ๋ฉด ๋ ๋ฏํ๋ค.
๋๋น์ฐ์ ํ์์ผ๋ก ํ ๋๋ ๋ฐฑํธ๋ํน์ด ํ์ํ ๊ฒ ๊ฐ์์ ์คํ๋ ค ๊น์ด์ฐ์ ํ์ ํ์ด๊ฐ ๋ ์ง๊ด์ ์ธ ๋๋์ด๋ค..!
๋์ ํ์ด
#include <string>
#include <vector>
#include <iostream>
#include <map>
using namespace std;
int graph[18][18] = {0,};
vector<vector<int>> edges;
vector<int> info;
map<int, vector<int>> m;
int answer = 0;
int sheepCount = 0;
void dfs(int index, int sheep, int wolf, vector<int> canGo){
if(sheep <= wolf) return;
if(sheep == sheepCount) {
answer = sheep; return;
}
if(answer<sheep) answer = sheep;
for(int node: m[index]){ // ๊ฐ ์ ์๋ ๋
ธ๋ ํ์
canGo.push_back(node);
}
for(int i=0; i<canGo.size(); ++i){
vector<int> newGo = canGo;
newGo.erase(newGo.begin()+i);
// ํ์ฌ ๋
ธ๋๋ง ์ญ์ (์ค๋ณต๋ฐฉ์ง), ๋ค๋ฅธ ๋
ธ๋๋ ๋ฐฉ๋ฌธ๊ฐ๋ฅํ๋ฏ๋ก ๋จ๊ฒจ์ผ ํจ
if(info[canGo[i]]==0) dfs(canGo[i], sheep+1, wolf, newGo);
else dfs(canGo[i], sheep, wolf+1, newGo);
}
}
int solution(vector<int> i, vector<vector<int>> e) {
// ๋ฐฑํธ๋ํน?
edges = e;
info = i;
for(auto edge : e){
m[edge[0]].push_back(edge[1]);
}
for(int n: i){
if(n==0) sheepCount++;
}
vector<int> canGo; // ๊ฐ ์ ์๋ ์์๋
ธ๋ ๋ชฉ๋ก
dfs(0,1,0,canGo);
return answer;
}
'๐ ์๊ณ ๋ฆฌ์ฆ > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++/PGS] Lv.3 : ๋์คํฌ ์ปจํธ๋กค๋ฌ (Heap/priority_queue) (0) | 2025.04.17 |
---|---|
[C++/PGS] Lv.4 : ํธํ ๋ฐฉ ๋ฐฐ์ (์ฌ๊ท) (0) | 2025.04.16 |
[C++/PGS] Lv.3 : ์ฐ์ ํ์ค ๋ถ๋ถ ์์ด์ ํฉ (DP) (0) | 2025.04.15 |
[C++/PGS] Lv.3 : ์ง๊ฒ๋ค๋ฆฌ ๊ฑด๋๊ธฐ (0) | 2025.04.14 |
[Javascript/PGS] Lv.2 : ์ฐ์ ๋ถ๋ถ ์์ด ํฉ์ ๊ฐ์ (1) | 2025.04.14 |