Problems/205. 01 Matrix

205. 01 Matrix

MediumMatrixGraphMedium

Given an m x n binary grid where cells contain either 0 or 1, calculate the distance from each cell to the nearest 0 cell. The distance between two adjacent cells (horizontally or vertically) is defined as 1.

Example 1
Input: grid = [ [0, 0, 0], [0, 1, 0], [1, 1, 1] ]
Output: [ [0, 0, 0], [0, 1, 0], [1, 2, 1] ]
The cell at (1,1) is at distance 1 from a 0. The cell at (2,1) is at distance 2 from the nearest 0, which is at (1,1)'s neighbors.
Example 2
Input: grid = [ [0], [1] ]
Output: [ [0], [1] ]
The cell at (1,0) is directly adjacent to the 0 at (0,0), so its distance is 1.
Example 3
Input: grid = [ [0, 1], [0, 0] ]
Output: [ [0, 1], [0, 0] ]
The cell at (0,1) is next to the zeros at (0,0) and (1,1), giving a distance of 1.
Visualizer

Visualizer will appear here