STUDY/알고리즘

[프로그래머스] 무인도 여행 (javascript)

디리릭 2023. 9. 8. 00:38
728x90

 

이 문제는 재귀식을 이용하여 해결했다. 

현재 위치에서 위,아래,양옆으로 이동가능 하기 때문에 현재 위치를 이동해보며 무인도 경계까지 값을 더하는 함수를 만들었다. 

 

재귀함수에서 break point를 먼저 정의 하고 재귀함수를 호출 부분을 추가로 구현했다. 

 

const map_arr = [];

function solution(maps) {
    var answer = [];
    maps.forEach(d=>map_arr.push([...d]))
    console.log(map_arr);
    
    for(i=0; i<map_arr.length; i++){
        for(j=0; j< map_arr[i].length;j++){
            if(map_arr[i][j] === 'X')
                continue;
            
            //무인도를 찾음
            answer.push(calculateIsland(i, j));
        }
    }
    
    if(answer.length === 0)
        return [-1];
    
    return answer.sort((a,b)=>a-b);
}

function calculateIsland(i, j){
    if(i<0 || j<0 || i>=map_arr.length || j>=map_arr[0].length ){
        return 0;
    }
    if(map_arr[i][j] === 'X'){
        return 0;
    }
    const score = Number(map_arr[i][j]);
    map_arr[i][j] = 'X';
    return score + calculateIsland(i-1,j) + calculateIsland(i+1,j) + calculateIsland(i,j-1)+ calculateIsland(i,j+1);
}

 

https://school.programmers.co.kr/learn/courses/30/lessons/154540

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

728x90