Skip to content

Commit 5e9bdd3

Browse files
committed
[Week14] PGS 92343: 양과늑대
1 parent dad97f2 commit 5e9bdd3

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// 양과늑대
2+
// 백트래킹
3+
/**
4+
* 어려워서 ai 활용
5+
* ArrayList로 이진 트리를 구성하여, 해당 노드의 자식들을 간편하게 접근할 수 있도록 함.
6+
* backtrack 내부에선 currentIdx 를 기반으로 양인지, 늑대인지 구분하고 값을 증가시킨다.
7+
* 만약 늑대가 더 많아진다면 가지치기(return)
8+
* 그 다음 result를 업데이트(양 개수)
9+
* 다음 탐색은 현재 노드 기반 자식 노드들을 찾고, 찾은 자식들에 대해 백트래킹을 진행
10+
* 현재 가능한 방향으로만 backtrack 함수를 호출하기 때문에 visited 배열 불필요
11+
*/
12+
public class PGS_92343 {
13+
class Solution {
14+
15+
static int result;
16+
static List<Integer>[] tree;
17+
18+
public int solution(int[] info, int[][] edges) {
19+
result = 0;
20+
int n = info.length;
21+
tree = new ArrayList[n];
22+
23+
for(int i=0; i<n; i++){
24+
tree[i] = new ArrayList<>();
25+
}
26+
27+
for(int[] edge: edges){
28+
tree[edge[0]].add(edge[1]);
29+
}
30+
31+
List<Integer> nextNodes = new ArrayList<>();
32+
nextNodes.add(0);
33+
34+
backtrack(0, 0, 0, nextNodes, info);
35+
36+
return result;
37+
}
38+
39+
private void backtrack(int currIdx, int sheep, int wolf, List<Integer> nextNodes, int[] info) {
40+
if(info[currIdx] == 0){
41+
sheep++;
42+
}else{
43+
wolf++;
44+
}
45+
46+
// 늑대가 양과 같거나 많아지면 탐색 종료
47+
if(wolf >= sheep)return;
48+
49+
result = Math.max(result, sheep);
50+
51+
// 다음으로 갈 수 있는 노드 목록 업데이트 (현재 노드는 제외, 현재 노드의 자식들은 추가)
52+
List<Integer> list = new ArrayList<>(nextNodes);
53+
// remove(Object o) 형식이여야, o 에 해당하는 "값" 을 찾아 지운다.
54+
list.remove(Integer.valueOf(currIdx));
55+
56+
for(int child : tree[currIdx]){
57+
list.add(child);
58+
}
59+
60+
for(int next : list){
61+
backtrack(next, sheep, wolf, list, info);
62+
}
63+
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)