I have a binary matrix with 0 and 1, and given integer K >=0. Now I want to find all possible cells which are at a maximum distance of K from cells with the value 1 and mark them as some letter 'x'.
The distance between cells A[5][2] and A[1][4] is |1-5|+|4-2|=6.
Example:
A 8x8 matrix and K = 2, cells with value 1 at (2,2) and (6,6)
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0
Output:
0 0 x 0 0 0 0 0
0 x x x 0 0 0 0
x x 1 x x 0 0 0
0 x x x 0 0 0 0
0 0 x 0 0 0 x 0
0 0 0 0 0 x x x
0 0 0 0 x x 1 x
0 0 0 0 0 x x x
This is my logic which I am attempting:
find the cell position for 1 and find all cells starting from row -k till +k for given column. Similarly find all cells with given row and columns ranging from -k till +k. So for above example, for (2,2) the cells based on my logic are (0,2), (1,2), (2,2), (3,2) , (4,2) and then (2,0) , (2,1) , (2,2) , (3,2), (4,2).
But I am not able to understand how to get the remaining cells surrounding (2,2) which are (1,1), (1,3) and (3,1) , (3,3).
Matrix is of size m rows and n cells in range 1 to 500
K range is 1 to 1000