# LeetCode: Shortest Path In Binary Matrix Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[][]} grid3 * @return {number}4 */5var shortestPathBinaryMatrix = function (grid) {6  const N = grid.length7  const visited = Array.from({ length: N }, _ => Array(N).fill(false))8  const queue = []9
10  if (grid[0][0] || grid[N - 1][N - 1]) {11    return -112  }13
14  visited[0][0] = true15  queue.unshift([0, 0, 1])16  while (queue.length) {17    const [x, y, shortest] = queue.pop()18    if (x === N - 1 && y === N - 1) {19      return shortest20    }21    for (const [i, j] of [22      [x - 1, y - 1],23      [x - 1, y],24      [x - 1, y + 1],25      [x, y - 1],26      [x, y + 1],27      [x + 1, y - 1],28      [x + 1, y],29      [x + 1, y + 1],30    ]) {31      if (0 <= i && i < N && 0 <= j && j < N && !grid[i][j] && !visited[i][j]) {32        visited[i][j] = true33        queue.unshift([i, j, shortest + 1])34      }35    }36  }37
38  return -139}```

leetcode

graph

bfs

## Next Post

LeetCode: Is Graph Bipartite

Feb 15, 2021

Search Posts