Distance To Nearest 1 in a Binary Matrix Problem
Given a binary matrix MAT
containing only 0s and 1s of size N x M, find the distance of the nearest cell containing 1 for each cell in the matrix.
The distance is calculated as |i1 – i2| + |j1 – j2|, where (i1, j1) are the coordinates of the current cell and (i2, j2) are the coordinates of the nearest cell containing value 1.
Note: Movements are only allowed in four directions: Up, Down, Left, and Right.
Input:
The first line contains an integer 'T' denoting the number of test cases. For each test case, the first line contains two space-separated integers ‘N’ and ‘M’ representing the number of rows and columns respectively.
N subsequent lines contain M space-separated integers representing the elements of the matrix.
Output:
For each test case, print a matrix of the same dimensions where each cell contains the distance to the nearest cell with a 1.
Example:
Input:
N = 3, M = 4
mat[][] = {
0, 0, 0, 1,
0, 0, 1, 1,
0, 1, 1, 0
}
Output:
3 2 1 0
2 1 0 0
1 0 0 1
Constraints:
- 1 <= T <= 5
- 1 <= N <= 2*10^2
- 1 <= M <= 2*10^2
Additional Notes:
You do not need to print anything; the function should only implement the logic to produce the required output.
Given a binary matrix, find the distance of the nearest cell having 1 in the matrix for each cell.
Use BFS to traverse the matrix and find the nearest cell having 1 for each cell.
Initialize the output ...read more
Top Dunzo Software Developer interview questions & answers
Popular interview questions of Software Developer
Reviews
Interviews
Salaries
Users/Month