01-matrix.sh — zsh
matrixgraphbfsqueue

You are given an m x n binary matrix mat containing only 0s and 1s. Return a matrix of the same size where each cell stores the distance to the nearest 0, using 4-directional moves (up, down, left, right).

Input / output

  • Input: mat: int[][]
  • Output: int[][] (distance from each cell to its nearest 0)

Examples

  1. mat = [[0,0,0],[0,1,0],[0,0,0]] returns [[0,0,0],[0,1,0],[0,0,0]] because every 0 stays at distance 0 and the center 1 is one step from a zero.
  2. mat = [[0,0,0],[0,1,0],[1,1,1]] returns [[0,0,0],[0,1,0],[1,2,1]]; the bottom-middle cell is two moves away from its nearest zero.
  3. mat = [[0]] returns [[0]].

Constraints

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

Follow-up How would the algorithm change if diagonal moves were allowed, or if you needed to answer many nearest-zero queries against the same static matrix?

Examples
Example 1
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]
Example 2
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]
Example 3
Input: mat = [[0]]
Output: [[0]]