Problem
You get a matrix mat with m rows and n columns. Each cell holds 0 or 1, and at least one cell holds 0.
From a cell, you can move one step up, down, left or right. The distance between two cells is the smallest number of steps from one cell to the other.
Return a matrix of the same size. In each cell, put the distance from that cell to the nearest cell that holds 0.
Example 1
- Input:
- mat = [[0,1,1],[1,1,1],[1,1,0]]
- Output:
- [[0,1,2],[1,2,1],[2,1,0]]
- Explanation:
- The center cell is 2 steps from the 0 in the top-left corner. It is also 2 steps from the 0 in the bottom-right corner.
Example 2
- Input:
- mat = [[1,1,1,0]]
- Output:
- [[3,2,1,0]]
Constraints
- m == mat.length
- n == mat[i].length
- 1 <= m, n <= 10^4
- 1 <= m * n <= 10^4
- mat[i][j] is 0 or 1
- At least one cell of mat holds 0
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
Sources · 1 reference
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 1 record
No company association
Leetcode 542. 01 Matrix
Reported date not specified · 0 source reports
Source snapshot: Nov 12, 2026
View source