SDE & MLE Prep

1091. Shortest Path in Binary Matrix

Problem

In an n×n binary grid, find the shortest clear path from the top-left to the bottom-right cell: it visits only 0 cells and moves in any of the 8 directions. Return its length in cells, or −1 if there is none.

Example: [[0,1],[1,0]] → 2; [[0,0,0],[1,1,0],[1,1,0]] → 4

Constraints: n ≤ 100.

BFS over 8 directions from (0,0) to (n−1,n−1); path length counts cells.

Complexity: O(n²).

class Solution:
    def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
        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 == 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