Skip to main content
LeetCode 542, Medium. Topics: Array, Dynamic Programming, Breadth-First Search, Matrix. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 13 parametrized pytest cases, and a playground notebook:

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
Example 2

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

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Grind 75, Grind.
Last modified on August 25, 2026