본문 바로가기

알고리즘/Lv. 2

프로그래머스 87946 피로도 자바 풀이

728x90

난이도 : Lv. 2

풀이일 : 2412242

https://school.programmers.co.kr/learn/courses/30/lessons/87946?language=python3

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


문제


풀이 코드

class Solution {
    int answer = -1;
    boolean[] visited;
    
    public int solution(int k, int[][] dungeons) {
        visited = new boolean[dungeons.length];
        DFS(k, 0, dungeons);
        
        return answer;
    }
    
    public void DFS(int hp, int depth, int[][] dungeons) {
        if (depth > answer) {
            answer = depth;
        }
        for (int i = 0; i < dungeons.length; i++) {
            if (!visited[i] && hp >= dungeons[i][0]) {
                visited[i] = true;
                DFS(hp - dungeons[i][1], depth + 1, dungeons);
                visited[i] = false;
            }
        }   
        return;
    }
}
  • DFS로 탐색 진행
  • 현재 depth가 answer보다 크다면, answer 재할당
  • 던전목록 길이만큼 반복하며 방문할 수 있는 던전이라면 방문 후 DFS 재귀 호출

제출 화면