완전 탐색인데 생각보다 까다로웠던 문제.
어떻게 풀어야하는지는 알았는데 구현이 어려웠다..!
import java.util.*;
class Solution {
private int[] info;
private Map<Integer, Set<Integer>> tree;
public int solution(int[] info, int[][] edges) {
this.info = info;
this.tree = new HashMap<>();
for (int i = 0; i < info.length; i++) {
tree.put(i, new HashSet<>());
}
for (int[] edge : edges) {
tree.get(edge[0]).add(edge[1]);
}
Set<Integer> nextPossible = new HashSet<>(tree.get(0));
return dfs(0, 0, 0, nextPossible);
}
private int dfs(int sheep, int wolf, int current, Set<Integer> possible) {
if (info[current] == 0) {
sheep++;
} else {
wolf++;
}
if (wolf >= sheep) {
return 0;
}
int maxSheep = sheep;
for (int next : possible) {
Set<Integer> nextPossible = new HashSet<>(possible);
nextPossible.remove(next);
nextPossible.addAll(tree.get(next));
maxSheep = Math.max(maxSheep, dfs(sheep, wolf, next, nextPossible));
}
return maxSheep;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 택배 배달과 수거하기 (3) | 2024.10.26 |
---|---|
[프로그래머스] 블록 이동하기 (0) | 2024.10.20 |
[프로그래머스] 합승 택시 요금 (1) | 2024.10.13 |
[프로그래머스] 파괴되지 않은 건물 (1) | 2024.09.30 |
[프로그래머스] 양궁 대회 (0) | 2024.09.23 |