Python Numpy Track all 0's in an explosive spread

Viewed 71

Question:

I have a python numpy array list that is of RxC dimensions containing all 1's except one place with a 0.

Lets say we have 3x4 for now. And I have to track its adjacent from 0 point on to see the explosive spread of it.

Check input for visual representation of the context.

Its related to chain reaction spread, But I can't wrap my head around on how i can track it in a 2D array.

There can be `N' number of zero's and How do I mark all its surrounding Places as 0 as well.

What I tried:

I tried doing some math over it but works only for one place with this formula

0 - position 3,3

size - 3x4

3-3, 4-3 = 1 iteration. But its wrong.

Input:

Starting:

[
[1,1,1,1],
[1,1,1,1],
[1,1,0,1],
[1,1,1,1]
]

Iteration 1:

[
[1,1,1,1],
[1,0,0,0],
[1,0,0,0],
[1,0,0,0]
]

Iteration 2:

[
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]

Output:

The chain reaction spread took 2 iterations to complete.

1 Answers

IIUC, use scipy.ndimage.distance_transform_cdt:

from scipy.ndimage import distance_transform_cdt

arr = np.ones((4, 4))
arr[2,2] = 0
distance_transform_cdt(arr)

Output:

array([[2, 2, 2, 2],
       [2, 1, 1, 1],
       [2, 1, 0, 1],
       [2, 1, 1, 1]])

You can max it to get n

distance_transform_cdt(arr).max()
# 2

Tested with 2 zeros:

arr2 = np.ones((5, 5))
arr2[2,3] = 0
arr2[1,1] = 0
arr2

array([[1., 1., 1., 1., 1.],
       [1., 0., 1., 1., 1.],
       [1., 1., 1., 0., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

distance_transform_cdt(arr2)

array([[1, 1, 1, 2, 2],
       [1, 0, 1, 1, 1],
       [1, 1, 1, 0, 1],
       [2, 2, 1, 1, 1],
       [3, 2, 2, 2, 2]])
Related