【发布时间】:2015-10-31 12:19:22
【问题描述】:
我需要编写一个函数def amountofNeighbours(row, column) 来打印矩阵中某个元素的邻居数量。例如,给定矩阵[[2, 3, 4], [5, 6, 7], [8, 9, 10]],元素 2 在位置 [0][0] 处有三个邻居,而元素 6 在位置 [1][1] 处有八个邻居。我不确定处理此类问题的最佳方法是什么。我经历了所有的可能性,这给了我以下信息:
def amountofNeighbours(row, column):
neighbours = 0
for i in range(row):
for j in range(column):
if i == 0 and j == 0 or i == 0 and j == column - 1:
neighbours = 3
elif i == row - 1 and j == 0 or i == row-1 and j == column - 1:
neighbours = 3
elif i > 0 and j == 0 or i == 0 and j > 0:
neighbours = 5
elif i == row - 1 and j > 0:
neighbours = 5
elif j == column - 1 and i > 0:
neighbours = 5
else:
neighbours = 8
return neighbours
当我用 amountofNeighbours(1, 1) 调用它时,它给了我正确的答案,即 3,但如果我用 amountofNeighbours(2,2) 调用它,答案应该是 8,而它给了我 3。有人有改进的想法吗?
【问题讨论】: