Distance to the nearest 0
Standard · Write code · about 20 min
Each cell of mat is 0 or 1. For every cell, find how many steps (up, down, left or right) it takes to reach the nearest 0.
Return a matrix of the same size with those distances.
Example 1
Input:
[[[0,0,0],[0,1,0],[1,1,1]]]
Output:
[[0,0,0],[0,1,0],[1,2,1]]
The middle of the bottom row is 2 steps from the nearest 0.
Example 2
Input:
[[[0,1,1],[1,1,1],[1,1,1]]]
Output:
[[0,1,2],[1,2,3],[2,3,4]]
One 0 in the corner: distances grow diagonally.
Constraints
- 1 ≤ rows, cols ≤ 100
- mat[r][c] is 0 or 1
- mat has at least one 0
Learn the idea first: 0-1 BFS and multi-source BFS, a visual lesson.
More 0-1 BFS and multi-source BFS problems
- Front or back of the deque Warm-up
- Which structure for 0 and 1 weights? Warm-up
- Rotting oranges Standard
- Minimum obstacle removal Standard