반응형
[문제링크]
https://programmers.co.kr/learn/courses/30/lessons/92343
코딩테스트 연습 - 양과 늑대
[0,0,1,1,1,0,1,0,1,0,1,1] [[0,1],[1,2],[1,4],[0,8],[8,7],[9,10],[9,11],[4,3],[6,5],[4,6],[8,9]] 5 [0,1,0,1,1,0,1,0,0,1,0] [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6],[3,7],[4,8],[6,9],[9,10]] 5
programmers.co.kr
[설명]
이 문제도 처음에 풀지 못하였습니다. 다른 사람들의 풀이를 보고 이해한 뒤 DFS로 풀었습니다.
1) childs라는 ArrayList를 만들어 edges를 입력해준다.
2) DFS를 돌린다.
3) 해당 위치의 info가 0일 경우 sheepcount++, 1일 경우 wolfcount++를 해준다.
4) maxSheepCount를 업데이트 해준다.
5) 만약 wolfCount가 더 많다면 return 해준다.
6) nextNodes의 방문 노드들에 childs[node]를 전부 더해준다.
프로그래머스 2022 KAKAO BLIND RECRUITMENT - 양과 늑대 JAVA풀이
import java.util.*;
class Solution {
public int maxSheepCount;
public ArrayList<Integer>[] childs;
public int solution(int[] info, int[][] edges) {
childs = new ArrayList[info.length];
for(int[] link : edges){
int parent = link[0];
int child = link[1];
if(childs[parent] == null) {
childs[parent] = new ArrayList<>();
}
childs[parent].add(child);
}
List<Integer> nextNodes = new ArrayList<>();
nextNodes.add(0);
DFS(0, 0, 0, nextNodes, info);
return maxSheepCount;
}
public void DFS(int sheepCount, int wolfCount, int node, List nextNodes, int[] info){
sheepCount += info[node] == 1?0:1;
wolfCount += info[node];
maxSheepCount = Math.max(maxSheepCount, sheepCount);
if(sheepCount <= wolfCount) {
return;
}
List<Integer> temp = new ArrayList<>();
temp.addAll(nextNodes);
if(childs[node] != null){
temp.addAll(childs[node]);
}
temp.remove(Integer.valueOf(node));
for(int nextNode : temp){
DFS(sheepCount, wolfCount, nextNode, temp, info);
}
}
}
궁금하신 부분이나 부족한 점은 댓글로 알려주시면 감사하겠습니다.
'알고리즘 > DFS_BFS' 카테고리의 다른 글
BJ G5 7569 토마토 - Java (1) | 2024.10.01 |
---|---|
BJ_G4_14502_연구소 - Java (0) | 2022.10.07 |
BJ_S2_10819_차이를최대로 - Java (0) | 2022.06.08 |
BJ_S1_1389_케빈베이컨의6단계법칙 - Java (0) | 2022.06.07 |
2022 KAKAO BLIND RECRUITMENT - 양궁대회 (0) | 2022.06.05 |
댓글