01 Matrix

Given an m x n binary matrix mat, return a matrix of the same size where each cell holds the distance to the nearest 0. Two cells sharing an edge are at distance 1.

30:00

01 Matrix
medium
Free written solution
Topics
Companies

Given an m x n binary matrix mat, return a matrix of the same size where each cell holds the distance to the nearest 0. Two cells sharing an edge are at distance 1.

Example 1:
Input: {"mat":[[0,0,0],[0,1,0],[0,0,0]]}
Output: [[0,0,0],[0,1,0],[0,0,0]]
Constraints:
  • m=mat.lengthm = \text{mat.length}, n=mat[i].lengthn = \text{mat[i].length}

  • 1≤m,n≤1041 \leq m, n \leq 10^4

  • 1≤m⋅n≤1041 \leq m \cdot n \leq 10^4

  • mat[i][j]\text{mat[i][j]} is either 0 or 1.

  • There is at least one 0 in mat.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"mat":[[0,0,0],[0,1,0],[0,0,0]]}

Make a 3 x 3 distance grid filled with -1, meaning "not reached yet".

no wave yet

reached 0 / 9

0

0

0

0

?

0

0

0

0

queue (0)

empty

0 (source)
leaving queue
just reached
already set
Arrows show which way the wave travelled into a cell.
Variables
VariableValue
m3
n3
queue0
wave-
DepthFunction Call
Stack empty
0/12