Leetcode 1091. Shortest Path in Binary Matrix

siwoo jang·2024년 1월 29일
0

  • 출발지와 목적지가 막혀있을 경우에는 경로가 없으므로 -1 반환

  • 이동할 8방향 x,y 좌표를 dirs 에 미리 저장
    x, y, 경로 길이를 담은 queue 를 생성

  • queue 길이가 0이거나 목적지에 도착할때까지 while 문 반복
    현재 길이를 queue.shift()로 값을 받고

  • for문을 돌려 현재 x,y값에다가 각각 dirs 값들을 더해서 nextX, nextY 만들고
    nextX, nextY 가 범위를 벗어나면 continue 로 스킵
    이동했으면 queue 갱신해주고 이동한 자리이므로 1로 값 갱신

var shortestPathBinaryMatrix = function(grid) {
    
    if(grid[0][0]===1 || grid[grid.length-1][grid[0].length-1] === 1 ){
        return -1;
    }
    
    let dirs = [ [-1,-1],[-1,0],[-1,1],
                [0,-1]/*cur*/,[0,1],
                [1,-1],[1,0],[1,1] ];
    let queue = [[0,0,1]];
    
    while(queue.length){
        let [curX,curY,cnt] = queue.shift();
        
        if(curX === grid.length -1 && curY === grid[0].length-1)
            return cnt;
        
        for(let [x,y] of dirs){
            let [nextX,nextY] = [curX+x,curY+y];
            
            if(nextX<0 || nextX>grid.length-1 || nextY<0 || nextY>grid[0].length -1 || grid[nextX][nextY]===1)
                continue;
            
            queue.push([nextX,nextY,cnt+1])
            grid[nextX][nextY] = 1;
        }
    }
    
    return -1;
    
};
profile
프론트/백엔드 개발자입니다

0개의 댓글