sagelearnai

Shortest Path in Binary Matrix

Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #1091

In an n × n binary grid, find the length of the shortest clear path from the top-left to the bottom-right cell. A clear path visits only 0 cells and moves in any of the 8 directions. The length counts the number of cells visited. Return -1 if there's no such path.

Examples

text
[[0,1],[1,0]]                 →  2
[[0,0,0],[1,1,0],[1,1,0]]     →  4
[[1,0,0],[1,1,0],[1,1,0]]     →  -1   (start is blocked)

Hints

  1. Unweighted shortest path means BFS.
  2. Mark cells visited when you enqueue them, not when you dequeue, or the same cell gets enqueued many times.

Approach

If the start or the end is 1, return −1. Otherwise BFS from (0,0) with distance 1, checking 8 neighbors and marking the grid as you enqueue. The first time you pop (n-1, n-1), return its distance.

A\* with the Chebyshev distance max(|dr|, |dc|) as heuristic is a common follow-up. It's admissible for 8-directional moves and explores far fewer cells on open grids.

Complexity

Time: O(n²). Space: O(n²).

Python solution
from collections import deque

def shortestPathBinaryMatrix(grid):
    n = len(grid)
    if grid[0][0] or grid[n - 1][n - 1]:
        return -1
    q = deque([(0, 0, 1)])
    grid[0][0] = 1
    while q:
        r, c, d = q.popleft()
        if r == n - 1 and c == n - 1:
            return d
        for dr in (-1, 0, 1):
            for dc in (-1, 0, 1):
                nr, nc = r + dr, c + dc
                if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0:
                    grid[nr][nc] = 1
                    q.append((nr, nc, d + 1))
    return -1
JavaScript solution
function shortestPathBinaryMatrix(grid) {
  const n = grid.length;
  if (grid[0][0] || grid[n - 1][n - 1]) return -1;
  const q = [[0, 0, 1]];
  grid[0][0] = 1;
  for (let h = 0; h < q.length; h++) {
    const [r, c, d] = q[h];
    if (r === n - 1 && c === n - 1) return d;
    for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
      const nr = r + dr, nc = c + dc;
      if (nr >= 0 && nc >= 0 && nr < n && nc < n && grid[nr][nc] === 0) { grid[nr][nc] = 1; q.push([nr, nc, d + 1]); }
    }
  }
  return -1;
}