Skip to content

Latest commit

 

History

History
42 lines (34 loc) · 1.14 KB

File metadata and controls

42 lines (34 loc) · 1.14 KB

Screen Shot 2022-08-13 at 16 03 56

Screen Shot 2022-08-13 at 16 04 06

/**
 * @param {number[][]} grid
 * @return {number}
 */
var shortestPathBinaryMatrix = function(grid) {
    let dirs = [
        [0, -1],
        [0, 1],
        [1, -1],
        [1, 0],
        [1, 1],
        [-1, -1],
        [-1, 0],
        [-1, 1]
    ]
    
    if(grid[0][0] === 1) return -1;
    let queue = [[0, 0, 1]];
    
    while(queue.length) {
        let [x, y, path] = queue.shift();
        if(x === grid.length - 1 && y === grid.length - 1) return path;
        
        for(let [dx, dy] of dirs) {
            let row = x + dx;
            let col = y + dy;
            
            if(row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] !== 0) continue;
            queue.push([row, col, path + 1]);
            grid[row][col] = 1;
        }
    }
    return -1
};