PS/프로그래머스

[DFS][JS]피로도

returnzero 2022. 7. 21. 21:08
function solution(k, dungeons) {
    var answer = -1;
    let visited= new Array(dungeons.length).fill(false);
    let max=0; 
    
    function DFS (health,count){
        
        max = Math.max(max, count);
        for(let i=0; i<dungeons.length;i++){
            if( visited[i]===false&& dungeons[i][0]<=health){
                visited[i]=true;
                health-= dungeons[i][1];
                // console.log("DFS", health, count+1);
                // console.log(health, visited);
                DFS(health, ++count)
                
                health+=dungeons[i][1];
                visited[i]=false;
                count--;
                // console.log(health, visited)
            }
        
        }
        
        
    }
    
    DFS(k, 0);
    answer=max;
    return max;
}

DFS는 가급적이면 재귀를 이용해서 구현할 생각을 해야 한다. DFS의 인자로는 health처럼 current state를 반영할 수 있는 것들을 넣어야 하며, count처럼 "답"으로서 요구하는 것을 넣어야 합니다. 또한, DFS를 재귀적으로 선언한 직후에는 다시 level를 거슬러올라가며 count, health등 state를 원상복구 해줄 수 있도록 DFS execution의 정반대를 실행해줘야 합니다.