Showing:
Handle Score
@Ibrahim Nash 5761
@akhayrutdinov 5111
@mb1973 4989
@Quandray 4944
@saiujwal13083 4506
@sanjay05 3762
@marius_valentin_dragoi 3516
@sushant_a 3459
@verma_ji 3341
@KshamaGupta 3318
Distance of nearest cell having 1
Medium Accuracy: 29.14% Submissions: 4745 Points: 4

Given a binary grid. Find the distance of nearest 1 in the grid for each cell.
The distance is calculated as |i1 – i2| + |j1 – j2|, where i1, j1 are the row number and column number of the current cell and i2, j2 are the row number and column number of the nearest cell having value 1.

Example 1:

Input: grid = {{0,1,1,0},{1,1,0,0},{0,0,1,1}}
Output: {{1,0,0,1},{0,0,1,1},{1,1,0,0}}
Explanation: The grid is-
0 1 1 0
1 1 0 0
0 0 1 1
0's at (0,0), (0,3), (1,2), (1,3), (2,0) and
(2,1) are at a distance of 1 from 1's at (0,1),
(0,2), (0,2), (2,3), (1,0) and (1,1)
respectively.


Example 2:

Input: grid = {{1,0,1},{1,1,0},{1,0,0}}
Output: {{0,1,0},{0,0,1},{0,1,2}}
Explanation: The grid is-
1 0 1
1 1 0
1 0 0
0's at (0,1), (1,2), (2,1) and (2,2) are at a
distance of 1, 1, 1 and 2 from 1's at (0,0),
(0,2), (2,0) and (1,1) respectively.


You don't need to read or print anything, Your task is to complete the function nearest() which takes grid as input parameter and returns a matrix of same dimensions where the value at index (i, j) in the resultant matrix signifies the minimum distance of 1 in the matrix from grid[i][j].

Expected Time Complexity: O(n*m)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ n, m ≤ 500

to report an issue on this page.

### Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?