例如,矩阵3x3
'0 1 2
3 4 5
6 7 8'
元素0的是1,3,4。
答案 0 :(得分:0)
# 2dMatrix: Your matrix
# x: x-coordinate of the element for which you're searching for neighbors
# y: y-coordinate of the element for which you're searching for neighbors
def nearest_elements_2dMatrix(2dMatrix, x,y):
upleft = 2dMatrix[x-1][y-1] if (x-1 >= 0 and y-1>=0) else None
downleft = 2dMatrix[x-1][y+1] if (x-1 >= 0 and y+1 < len(2dMatrix)) else None
left = 2dMatrix[x-1][y] if x-1 >= 0 else None
upright = 2dMatrix[x+1][y-1] if (x+1 < len(2dMatrix[0]) and y-1>=0) else None
right= 2dMatrix[x+1][y] if x+1 < len(2dMatrix[0]) else None
downright = 2dMatrix[x+1][y+1] if (x+1 < len(2dMatrix[0]) and y+1 < len(2dMatrix)) else None
above= 2dMatrix[x][y-1] if if y-1 >= 0 else None
below= 2dMatrix[x][y+1] if if y+1 < len(2dMatrix) else None
return [upleft, downleft, left, upright, right, downright, above, below]