개발관련/매일 코딩 테스트 챌린지

프로그래머스 무인도 버티기 자바스크립트

개발자 Dane 2023. 4. 15. 21:48
반응형
function solution(maps) {
    const xLen = maps.length
    const yLen = maps[0].length
    
    const vistedMap = Array.from(Array(xLen),()=>Array(yLen).fill(false))
    
    const offset = [
        [-1,0], //좌
        [1,0], //우
        [0,-1], //상
        [0,1], //하
    ]
    
    const answer = []
    
    function sumCountArea(x,y){
        const stack = [[x,y]]
        let count = maps[x][y]*1
        
        while(stack.length > 0){
            const [xP,yP] = stack.pop()
            offset.forEach(([moveX,moveY])=>{
                const nX = xP + moveX
                const nY = yP + moveY
                if(nX >= 0 && nX < xLen && nY >= 0 && nY < yLen && !vistedMap[nX][nY]  && maps[nX][nY] != "X"){
                    vistedMap[nX][nY] = true
                    count += maps[nX][nY]*1
                    stack.push([nX,nY])
                }
            })         
        }
        
        answer.push(count)
    }
    
    for(let i = 0; i < xLen; i++){
        for(let j = 0; j < yLen; j++){
            if(vistedMap[i][j] || maps[i][j] == "X"){
                continue
            }
            vistedMap[i][j] = true
            sumCountArea(i,j)
        }
    }
    console.log(answer)
    answer.sort((a,b)=>a-b)
    return answer.length > 0 ? answer: [-1]
}

 

총합, 최단거리

 

대부분 비슷하다.

 

2차배열이 주어질때

 

2차배열을 만들어서 방문여부를 체크하고

 

stack이나 que로 총합을 구하는게 비슷함

 

중요한건 루프문을 각자 짜는것

반응형