You are given a matrix having ‘N’ rows and ‘M’ columns. Each cell of the matrix can only contain three values as given below:
-1 -> It denotes a wall or an obstacle
0 -> It denotes a gate
2^31 - 1 = 2147483647 ( INF ) -> An infinitely large value denotes the empty room.
For each empty room (denoted by INF), you have to refill it with the distance to its nearest gate. If none of the gates is reachable from an empty room then the value ‘INF’ will remain as it is.
Example
For the matrix [[0,-1],[0,2147483647]] the updated matrix will be [[0,-1],[0,1]].
Note
The distance between two cells having their coordinates (x1,y1) and (x2,y2) are abs(x2-x1) + abs(y2-y1).
The first line of the input contains an integer ‘T’ denoting the number of test cases.
The next 2*T lines describe the ‘T’ test cases.
The first line of each test case contains two space-separated positive integers ‘N’ and ‘M’ denoting the number of the rows and columns in a matrix respectively.
The next ‘N’ lines of each test case contain ‘M’ space-separated integers among -1, 0, and 2^31 - 1.
Output Format:
The output of each test case should contain a matrix of size N x M where each empty cell will contain the distance to its nearest gate.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 10^4
1 <= M <= 10^4
1 <= N*M <= 10^4
Time Limit: 1 sec
2
2 2
2147483647 -1
-1 0
4 4
2147483647 -1 0 2147483647
2147483647 2147483647 2147483647 -1
2147483647 -1 2147483647 -1
0 -1 2147483647 2147483647
2147483647 -1
-1 0
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
Test case 1:
There is no path from the empty cell at [0.0] to the only gate at [1,1] .
Test case 2:

2
2 3
-1 0 2147483647
-1 0 2147483647
3 3
0 -1 2147483647
0 -1 2147483647
0 -1 2147483647
-1 0 1
-1 0 1
0 -1 2147483647
0 -1 2147483647
0 -1 2147483647
Perform BFS from each cell
O(N^2 * M^2), where ‘N’ is the number of rows and ‘M’ is the number of columns in the matrix.
We using two nested loops for traversing each element in a matrix that will take O(N * M) time.
For each cell, we perform a BFS which can traverse on all the elements in the worst case so it will take O(N*M) time.
Total time complexity O((N * M)^2)
O(N * M), where ‘N’ is the number of rows and ‘M’ is the number of columns in the matrix.
In the worst case, the BFS queue may contain ‘N * M’ cells.