기록하는 개발자

[프로그래머스][코딩테스트 고득점 Kit][Javascript] 게임 맵 최단거리 본문

Algorithm

[프로그래머스][코딩테스트 고득점 Kit][Javascript] 게임 맵 최단거리

밍맹030 2023. 8. 7. 20:47
728x90

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

 

프로그래머스

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

programmers.co.kr

function solution(maps) {
    const dx = [0, 0, 1, -1];
    const dy = [1, -1, 0, 0];
    const y = maps.length-1;
    const x = maps[0].length - 1;
    const queue = [[0, 0, 1]];

    while (queue.length) {
        const now = queue.shift();
        if (now[0] == y && now[1] == x) {
            return now[2];
        }
        // 상하좌우 탐색
        for (let i = 0; i < 4; i++) {
            const ny = now[0] + dy[i];
            const nx = now[1] + dx[i];
            
            // 상하좌우의 좌표가 0 이상이고
            // maps 내에 있고
            // 해당 좌표가 벽이 아닌 경우(벽이면 0)
            if (nx >= 0 && ny >= 0
                && nx <= x && ny <= y 
                && maps[ny][nx] === 1
               ) {
               	// maps 내 이미 지난 길을 0으로 표시
                maps[ny][nx] = 0;
                // now[2]+1 : 지나온 길의 총 거리
                queue.push([ny, nx, now[2]+1]);    
            }
        }
    }
    return -1;
}

 

728x90