这是一个 Ruby 解决方案。即使对于不熟悉 Ruby 的读者,该算法也应该是显而易见的。请注意我是如何计算要迭代的行和列的(在大多数语言中都会类似地编写)。在我看来,对于要迭代的行的索引,这比“从max(r-1, 0) 到min(r+1, arr.size-1)”要干净得多。
def adjacent(arr, r, c)
rows_ndx = arr.each_index.select { |i| (i-r).abs < 2 }
cols_ndx = arr.first.size.times.select { |j| (j-c).abs < 2 }
rows_ndx.each_with_object([]) do |i,a|
cols_ndx.each { |j| a << arr[i][j] unless [i,j] == [r,c] }
end
end
arr = [
[-1, 2, 3, 4],
[-2, 9, 1, 5],
[-3, 8, 7, 6],
[-4, -5, -6, -7]
]
(0..2).each do |i|
(0..3).each do |j|
puts "adjacent to #{arr[i][j]} at r=#{i}, c=#{j} = #{adjacent(arr, i, j)}"
end
end
打印
adjacent to -1 at r=0, c=0 = [2, -2, 9]
adjacent to 2 at r=0, c=1 = [-1, 3, -2, 9, 1]
adjacent to 3 at r=0, c=2 = [2, 4, 9, 1, 5]
adjacent to 4 at r=0, c=3 = [3, 1, 5]
adjacent to -2 at r=1, c=0 = [-1, 2, 9, -3, 8]
adjacent to 9 at r=1, c=1 = [-1, 2, 3, -2, 1, -3, 8, 7]
adjacent to 1 at r=1, c=2 = [2, 3, 4, 9, 5, 8, 7, 6]
adjacent to 5 at r=1, c=3 = [3, 4, 1, 7, 6]
adjacent to -3 at r=2, c=0 = [-2, 9, 8, -4, -5]
adjacent to 8 at r=2, c=1 = [-2, 9, 1, -3, 7, -4, -5, -6]
adjacent to 7 at r=2, c=2 = [9, 1, 5, 8, 6, -5, -6, -7]
adjacent to 6 at r=2, c=3 = [1, 5, 7, -6, -7]