Distance of nearest cell having 1 in a binary matrix

Given a matrix of integers A of size N x M consisting of 0 or 1.

For each cell of the matrix find the distance of nearest 1 in the matrix.

Distance between two cells (x1, y1) and (x2, y2) is defined as ** x1 - y1 + x2 - y2 **.

Find and return a matrix B of size N x M which defines for each cell in A distance of nearest 1 in the matrix A.

Note:

  1. Your solution will run on multiple test cases. If you are using global variables, make sure to clear them.

  2. There is atleast one 1 is present in the matrix.



Input Format

The first argument given is the integer matrix A.

Output Format

Return the matrix B.

Constraints

1 <= N, M <= 1000
0 <= A[i] <= 2

For Example

Input 1:
    A = [   [0, 0, 0, 1]
            [0, 0, 1, 1]
            [0, 1, 1, 0]   ]
Output 1:
        [   [3, 2, 1, 0]
            [2, 1, 0, 0]
            [1, 0, 0, 1]   ]

Input 2:
    A = [   [1, 0, 0]
            [0, 0, 0]
            [0, 0, 0]   ]
Output 2:
        [   [0, 1, 2]
            [1, 2, 3]
            [2, 3, 4]   ]
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Distance of nearest cell having 1 in a binary matrix on Interview Code Editor
Sign Up
to access hints and editorial solutions for Distance of nearest cell having 1 in a binary matrix

Discussion


Loading...
Click here to start solving coding interview questions