Geeksforgeeks

Error

×

Leaderboard

Showing:

Handle | Score |
---|---|

@Ibrahim Nash | 5761 |

@blackshadows | 5715 |

@akhayrutdinov | 5111 |

@mb1973 | 4989 |

@Quandray | 4944 |

@saiujwal13083 | 4506 |

@sanjay05 | 3762 |

@marius_valentin_dragoi | 3516 |

@sushant_a | 3459 |

@verma_ji | 3341 |

@KshamaGupta | 3318 |

Complete Leaderboard | |

Handle | Score |

@aroranayan999 | 1115 |

@bt8816103042 | 739 |

@SherlockHolmes3 | 447 |

@codeantik | 441 |

@SHOAIBVIJAPURE | 430 |

@shalinibhataniya1097 | 408 |

@ShamaKhan1 | 392 |

@neverevergiveup | 381 |

@amrutakashikar2 | 355 |

@mahlawatep | 353 |

@murarry3625 | 352 |

Complete Leaderboard |

Given a binary grid. Find the distance of nearest 1 in the grid for each cell.

The distance is calculated as **|i _{1} – i_{2}| + |j_{1} – j_{2}|**, where i

**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.

**Yout Task:**

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

Login to report an issue on this page.

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

Yes
Distance of nearest cell having 1

...