01 Matrix

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.

Note: This question is the same as 1765: https://leetcode.com/problems/map-of-highest-peak/

Example 1
0 0 0
0 1 0
0 0 0
Inputmat = [[0,0,0],[0,1,0],[0,0,0]]
Output[[0,0,0],[0,1,0],[0,0,0]]
Every 1 cell is adjacent to a 0, so its nearest distance is 1 and all 0 cells have distance 0.
Example 2
0 0 0
0 1 0
1 1 1
Inputmat = [[0,0,0],[0,1,0],[1,1,1]]
Output[[0,0,0],[0,1,0],[1,2,1]]
The bottom-middle cell is two edges away from the nearest 0, while the other 1 cells are one edge away.

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.

Asked at 15 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate