![]() |
VOOZH | about |
Given a binary grid[][]. Find the distance of the 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.
Note: There should be at least one cell with value 1 in the grid.
Examples:
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:
cell (0, 1) has nearest 1 at cell (0, 0) - distance = |0-0| + |0-1| = 1
cell (0, 2) has nearest 1 at cell (0, 3) - distance = |0-0| + |3-2| = 1
cell (1, 0) has nearest 1 at cell (0, 0) - distance = |1-0| + |0-0| = 1
cell (1, 1) has nearest 1 at cell (1, 2) - distance = |1-1| + |1-2| = 1
cell (2, 2) has nearest 1 at cell (2, 1) - distance = |2-2| + |2-1| = 1
cell (2, 3) has nearest 1 at cell (1, 3) - distance = |2-1| + |3-3| = 1
Rest all are cells having 1 so their distance from nearest celling having 1 is 0.Input: grid[][] = [[1, 0, 1],
[1, 1, 0],
[1, 0, 0]]
Output: [[0, 1, 0],
[0, 0, 1],
[0, 1, 2]]
Explanation:
cell (0, 0) has nearest 1 at cell (0, 1) - distance = |0-0| + |0-1| = 1
cell (0, 2) has nearest 1 at cell (0, 1) - distance = |0-0| + |2-1| = 1
cell (1, 0) has nearest 1 at cell (0, 1) - distance = |1-0| + |0-1| = 2
cell (1, 1) has nearest 1 at cell (1, 2) - distance = |1-1| + |1-2| = 1
cell (2, 0) has nearest 1 at cell (2, 1) - distance = |2-2| + |2-1| = 1
cell (2, 2) has nearest 1 at cell (2, 1) - distance = |2-2| + |2-1| = 1
Rest all are cells having 1 so their distance from nearest celling having 1 is 0.
Table of Content
The idea is to traverse the entire grid and compute the distance of each cell to the nearest 1:
- If the cell contains 1, its distance is 0.
- If the cell contains 0, we traverse the entire grid to find the nearest cell that contains 1.
- For each 0 cell, calculate the Manhattan distance to all cells with 1 and take the minimum distance.
Store this minimum distance in the corresponding cell of the result matrix. Repeat for all cells in the grid.
1 0 0 1 0 0 1 1 1 1 0 0
The problem can be efficiently solved using a multi-source BFS approach. Each cell in the grid is treated as a node, with edges connecting adjacent cells (up, down, left, right). Instead of running a separate search for every 0 cell, we enqueue all cells containing 1 at the start and perform a single BFS from these multiple sources simultaneously. As the BFS expands layer by layer, we update the distance of each unvisited 0 cell to be one more than its parent’s distance. This guarantees that every cell receives the minimum distance to the nearest 1 in an optimal and efficient manner.
1 0 0 1 0 0 1 1 1 1 0 0