Medium Accuracy: 31.5% Submissions: 3548 Points: 4

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

Input: The first line of input is an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of 2 lines. The first line of each test case contains two integers M and N denoting the number of rows and columns of matrix. Then in the next line are N*M space separated values of the matrix (mat) .

Output:
For each test case in a new line print the required distance matrix in a single line separated by space.

Your Task:
You don't need to read input or print anything. Your task is to complete the function nearest() which takes the matrix (mat) and its dimensions (N and M) as inputs 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 mat[i][j].
The distance is calculated as |i_{1} – i_{2}| + |j_{1} – j_{2}|, where i_{1}, j_{1} are the row number and column number of the current cell and i_{2}, j_{2} are the row number and column number of the nearest cell having value 1.

Expected Time Complexity: O(N*M). Expected Auxiliary Space: O(N*M).

Constraints:
1 <= T <= 50
1 <= N, M <= 1000
0 <= mat[i][j] <= 1

Example:
Input:
2
2 2
1 0 0 1
1 2
1 1

Output:
0 1 1 0
0 0

Explanation:
Testcase 1:
1 0
0 1
0 at {0, 1} and 0 at {1, 0} are at 1 distance from 1s at {0, 0} and {1, 1} respectively.