Shortest Path in Binary Matrix Problem
Description
LeetCode Problem 1091.
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:
- All the visited cells of the path are
0. - All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
The length of a clear path is the number of visited cells of this path.
Example 1:

Input: grid = [[0,1],[1,0]]
Output: 2
Example 2:

Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
Example 3:
Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
Output: -1
Constraints:
n == grid.lengthn == grid[i].length1 <= n <= 100grid[i][j] is 0 or 1
Solution
Approach: Breadth-First Search
Every step moves to one of the up to 8 neighboring cells, and all steps count the same, so breadth-first search from the top-left cell finds the shortest path. BFS visits the cells in layers: layer 1 is (0, 0), layer 2 is its clear neighbors, and so on. The first time we take (n - 1, n - 1) out of the queue, the layer number is the length of the path in cells.
If either the start or the end cell is 1, there is no clear path at all, so return -1 right away. A blocked start is the case that is easy to forget: the search would otherwise start from a cell that is not allowed.
To avoid visiting a cell twice, mark it as visited when it is added to the queue. Here we reuse the grid and set the cell to 1, which blocks it from then on. Doing it when adding a cell, not when removing it, keeps the same cell from being queued several times.
If the queue runs out before we reach the end, return -1. A 1 x 1 grid [[0]] returns 1: the path is the single cell.
Complexity: O(n2) time, each cell is queued at most once and has 8 neighbors. O(n2) space for the queue.
from collections import deque
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:
return -1
grid[0][0] = 1 # mark visited cells as blocked
q = deque([(0, 0)])
length = 1 # number of cells on the paths in the current layer
while q:
for _ in range(len(q)):
i, j = q.popleft()
if i == n - 1 and j == n - 1:
return length
for x in range(i - 1, i + 2):
for y in range(j - 1, j + 2):
if 0 <= x < n and 0 <= y < n and grid[x][y] == 0:
grid[x][y] = 1
q.append((x, y))
length += 1
return -1