> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Shortest Path in Binary Matrix Python Solution

> Tested Python solution for LeetCode 1091 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 1091, Medium. Topics: Array, Breadth-First Search, Matrix. [View on LeetCode](https://leetcode.com/problems/shortest-path-in-binary-matrix/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1091   # by problem number
lcpy gen -s shortest_path_in_binary_matrix   # by problem name
```

## Problem

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.

### Examples

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

```
Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
```

```
Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
Output: -1
```

### Constraints

* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/shortest_path_in_binary_matrix/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/shortest_path_in_binary_matrix/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque


class Solution:
    # Time: O(n^2)
    # Space: O(n^2)
    def shortest_path_binary_matrix(self, grid: list[list[int]]) -> int:
        if grid[0][0] == 1 or grid[-1][-1] == 1:
            return -1

        n = len(grid)
        if n == 1:
            return 1

        directions = [
            (-1, -1),
            (-1, 0),
            (-1, 1),
            (0, -1),
            (0, 1),
            (1, -1),
            (1, 0),
            (1, 1),
        ]
        queue: deque[tuple[int, int]] = deque([(0, 0)])
        grid[0][0] = 1
        while queue:
            row, col = queue.popleft()
            distance = grid[row][col]
            for dr, dc in directions:
                nr, nc = row + dr, col + dc
                if nr == n - 1 and nc == n - 1:
                    return distance + 1
                if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0:
                    grid[nr][nc] = distance + 1
                    queue.append((nr, nc))
        return -1
```

## Complexity

| Time   | Space  |
| ------ | ------ |
| O(n^2) | O(n^2) |

## Tags

[NeetCode All](/catalog/neetcode).
