|
| 1 | +/** |
| 2 | + * 1091. Shortest Path in Binary Matrix |
| 3 | + * https://leetcode.com/problems/shortest-path-in-binary-matrix/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. |
| 7 | + * If there is no clear path, return -1. |
| 8 | + * |
| 9 | + * A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the |
| 10 | + * bottom-right cell (i.e., (n - 1, n - 1)) such that: |
| 11 | + * - All the visited cells of the path are 0. |
| 12 | + * - All the adjacent cells of the path are 8-directionally connected (i.e., they are different |
| 13 | + * and they share an edge or a corner). |
| 14 | + * |
| 15 | + * The length of a clear path is the number of visited cells of this path. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[][]} grid |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var shortestPathBinaryMatrix = function(grid) { |
| 23 | + const size = grid.length; |
| 24 | + if (grid[0][0] === 1 || grid[size - 1][size - 1] === 1) return -1; |
| 25 | + |
| 26 | + const queue = [[0, 0, 1]]; |
| 27 | + const directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]; |
| 28 | + grid[0][0] = 1; |
| 29 | + |
| 30 | + while (queue.length) { |
| 31 | + const [row, col, distance] = queue.shift(); |
| 32 | + if (row === size - 1 && col === size - 1) return distance; |
| 33 | + |
| 34 | + for (const [deltaRow, deltaCol] of directions) { |
| 35 | + const newRow = row + deltaRow; |
| 36 | + const newCol = col + deltaCol; |
| 37 | + |
| 38 | + if (newRow >= 0 && newRow < size && newCol >= 0 |
| 39 | + && newCol < size && grid[newRow][newCol] === 0) { |
| 40 | + queue.push([newRow, newCol, distance + 1]); |
| 41 | + grid[newRow][newCol] = 1; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return -1; |
| 47 | +}; |
0 commit comments