01 Matrix
medium
matrix
graph
bfs
queue
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 nearest0)
Examples
mat = [[0,0,0],[0,1,0],[0,0,0]]returns[[0,0,0],[0,1,0],[0,0,0]]because every0stays at distance0and the center1is one step from a zero.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.mat = [[0]]returns[[0]].
Constraints
1 <= m, n <= 10^41 <= m * n <= 10^4mat[i][j]is0or1- There is at least one
0inmat
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]]