我在这个问题上挣扎了大约3周;我有一块板子(二维阵列):
0 0 0 -1 0 0 0 0 0 0
0 -1 0 0 0 0 0 -1 0 0
0 0 0 0 -1 0 0 0 -1 0
0 0 -1 -1 -1 0 0 0 0 0
0 0 0 0 0 0 0 0 -1 -1
其中-1
表示炸弹,我必须创建一个函数nearest_bombs(board, x,y):
,当用户放置x,y坐标时,该函数可以给我最近的炸弹坐标,例如在这种情况下:
用户输入:
x = 0
y = 0
要返回的值: (1,1)
现在,我已经在炸弹板上放置了炸弹的位置:
def where_bombs(board):
bombs = board
result = np.where(bombs == -1)
bombsCoordinates= list(zip(result[0], result[1]))
return bombsCoordinates
x=0
y=0
并计算最接近的一个:
def near_bomb(board,x,y):
b = [(x,y)]
a = where_bombs(board)
from scipy.spatial import distance
dist = distance.cdist(a, b, 'euclidean')
print (min(dist))
但是我在努力返回近距离的坐标,在这种情况下,近炸弹应该是(1,1)
。
只需替换最后一行near_bomb()
即可使用np.argmin()
:
def near_bomb(board,x,y):
b = [(x,y)]
a = where_bombs(board)
from scipy.spatial import distance
dist = distance.cdist(a, b, 'euclidean')
print (a[np.argmin(dist)])
argmin
返回最小值的值的参数(索引),然后可以使用该参数访问其中的相应坐标 a
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句