Return the distance from the nearest zero in a Python matrix

Given a matrix, finding the closest zero to a chosen reference point requires us to do the following:

  • Find the distances of all zeros from the reference point.

  • Select the point with the least distance.

Python matrix
Python matrix

The cell marked X is the chosen reference point and the cell colored orange is the nearest zero.

In the case above, the minimum distance is 2.236.

Solution

A brute-force solution is relatively simple as shown in the code below:

#import relevant libraries
import numpy as np
#randomly select reference point
i = np.random.randint(15)
j = np.random.randint(15)
print('Reference point [i,j]: [', i, ',',j, ']')
# randomly generate 15x15 matrix
arr = np.random.randint(10, size=(15, 15))
# find indexes of all zeros
zeros = np.argwhere(arr == 0)
#print('zeros: \n', zeros)
# find distances of all zeros from reference point
dist = np.sum((zeros-[i,j])**2, axis=1)
#print("distances, \n", dist)
# select point with minimum distance
index = np.argmin(dist)
# print the point and its distance
print('min_distance: ', np.sqrt(dist[index]), 'at ', zeros[index])

Explanation

  • Line 2: We import relevant libraries.

  • Line 5–7: We randomly select a reference point and print its coordinates.

  • Line 10: We randomly generate a 15x15 matrix.

  • Line 13: We find indexes of all zeros.

  • Line 17: We find the distances of all zeros from the reference point.

  • Line 21: We select the point with minimum distance.

  • Line 24: We print the point and its distance.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved