본문 바로가기
Coding Test/Programmers

[Programmers] (깊이/너비 우선 탐색(DFS/BFS)) Lv 2. 게임 맵 최단거리

by song.ift 2023. 2. 25.

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

 

프로그래머스

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

programmers.co.kr

 

function solution(maps) {
    return (bfs = (startY, startX) => {
        const [height, width] = [maps.length, maps[0].length],
            [queue, valueVisit] = [[], maps.map(i => i.map(v => 0))];
        const directionY = [0, 0, -1, 1],
            directionX = [-1, 1, 0, 0];

        queue.push([startY, startX]);
        valueVisit[startY][startX] = maps[startY][startX];

        while (queue.length) {
            const [y, x] = queue.shift();

            for (let i = 0; i < 4; i++) {
                const [nextY, nextX] = [y + directionY[i], x + directionX[i]];
                if (nextX < 0 || nextY < 0 || nextX >= width || nextY >= height) continue;
                if (!maps[nextY][nextX]) continue;
                if (valueVisit[nextY][nextX] && valueVisit[y][x] + maps[nextY][nextX] >= valueVisit[nextY][nextX]) continue;

                valueVisit[nextY][nextX] = maps[nextY][nextX] + valueVisit[y][x];
                queue.push([nextY, nextX]);
            }
        }
        
        return valueVisit[height - 1][width - 1] === 0 ? -1 : valueVisit[height - 1][width - 1];
    })(0, 0);
}

GitHub : https://github.com/developeSHG/Algorithm-Baekjoon_Programmers/tree/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/lv2/1844.%E2%80%85%EA%B2%8C%EC%9E%84%E2%80%85%EB%A7%B5%E2%80%85%EC%B5%9C%EB%8B%A8%EA%B1%B0%EB%A6%AC

 

GitHub - developeSHG/Algorithm-Baekjoon_Programmers: 백준 and 프로그래머스 소스코드

백준 and 프로그래머스 소스코드. Contribute to developeSHG/Algorithm-Baekjoon_Programmers development by creating an account on GitHub.

github.com

 

댓글