![]() |
VOOZH | about |
Given a binary grid of n*m. 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. There should be at least one 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: The grid is-
0 1 1 0
1 1 0 0
0 0 1 1
For cell at (0, 0), nearest 1 is at (0, 3). So distance = (0 – 0) + (3 – 0) = 3. Similarly, all the distance can be calculated. The following image shows distances to the nearest 1s.
👁 ImageInput: 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
The following image shows distances to the nearest 1s.
👁 Image
Table of Content
The idea is to traverse the matrix for each cell and find the minimum distance, To find the minimum distance traverse the matrix and find the cell which contains 1 and calculate the distance between two cells and store the minimum distance
Follow the given steps to solve the problem:
1 0 0 1 0 0 1 1 1 1 0 0
The idea is to use multisource Breadth-First Search. Consider each cell as a node and each boundary between any two adjacent cells be an edge. Number each cell from 1 to n*m. Now, push all the nodes whose corresponding cell value is 1 in the matrix in the queue. Apply BFS using this queue to find the minimum distance of the adjacent node for every 1 in the queue.
Follow the given steps to solve the problem:
Below is given the implementation:
1 0 0 1 0 0 1 1 1 1 0 0
In the above approach, we are creating a 2d array ans[][] of order n * m to store the results, but instead of doing so, we can modify the input array itself. The cells having value 1, will be marked 0, and the remaining cells will be marked INT_MAX, and we will operate similar to above approach.
1 0 0 1 0 0 1 1 1 1 0 0