본문 바로가기

코테

[Programmers] 게임 맵 최단거리

반응형

최단거리->큐

let visited = Array.from(new Array(100), () => new Array(100).fill(false));
let queue=[];

let dx = [0,0,1,-1];
let dy = [1,-1,0,0];

function solution(maps) {
    var answer = 0;
    queue.push([0,0,1]);
    while(queue.length!==0){
        let now = queue.shift();
        for(let i=0; i<4; i++){
            let x = now[0]+dx[i];
            let y = now[1]+dy[i];
            if(x<0 || y<0 || x>=maps.length || y>=maps[0].length){
                continue;
            }
            if(maps[x][y]===0)	continue;
            if(visited[x][y]){
                continue;
            }
            if(x===maps.length-1 && y===maps[0].length-1){
                return now[2]+1;
            }
            visited[x][y]=true;
            queue.push([x,y,now[2]+1]);
        }
    }
    return -1;
}
반응형

'코테' 카테고리의 다른 글

[Programmers] 위장 JS  (0) 2022.01.20
[Programmers] 삼각 달팽이 JS  (0) 2022.01.19
[Programmers] 가장 큰 수 JS  (0) 2022.01.19
[Programmers] 튜플 JS  (0) 2022.01.19
[Programmers] 124나라의 숫자 JS  (0) 2022.01.18