> ## 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.

# 01 Matrix Python Solution with Tests

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

LeetCode 542, Medium. Topics: Array, Dynamic Programming, Breadth-First Search, Matrix. [View on LeetCode](https://leetcode.com/problems/zero-one-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 542   # by problem number
lcpy gen -s zero_one_matrix   # by problem name
```

## Problem

Given an `m x n` binary matrix `mat`, return the distance of the nearest `0` for each cell.

The distance between two cells sharing a common edge is `1`.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg)

```
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]
```

![Example 2](https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg)

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

### Constraints

* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 10^4`
* `1 <= m * n <= 10^4`
* `mat[i][j]` is either `0` or `1`
* There is at least one `0` in `mat`

**Note:** This question is the same as 1765: [Map of Highest Peak](https://leetcode.com/problems/map-of-highest-peak/)

## Solution

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

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


class Solution:
    # Time: O(m * n)
    # Space: O(m * n)
    def update_matrix(self, mat: list[list[int]]) -> list[list[int]]:
        UNSEEN = -1  # noqa: N806
        m, n = len(mat), len(mat[0])
        queue: deque[tuple[int, int]] = deque()

        # Mark 1s as UNSEEN and add all 0s to queue
        for i in range(m):
            for j in range(n):
                if mat[i][j] == 0:
                    queue.append((i, j))
                else:
                    mat[i][j] = UNSEEN

        # BFS from all 0s simultaneously
        directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        while queue:
            row, col = queue.popleft()
            for dr, dc in directions:
                r, c = row + dr, col + dc
                if 0 <= r < m and 0 <= c < n and mat[r][c] == UNSEEN:
                    mat[r][c] = mat[row][col] + 1
                    queue.append((r, c))

        return mat
```

## Complexity

| Time      | Space     |
| --------- | --------- |
| O(m \* n) | O(m \* n) |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind).
