Đây là giải pháp Ruby. Thuật toán phải hiển nhiên ngay cả đối với những người đọc không quen thuộc với Ruby.
def adjacent(arr, r, c)
last_row, last_col = arr.size-1, arr.first.size-1
([r-1,0].max..[r+1,last_row].min).each_with_object([]) do |i, a|
([c-1,0].max..[c+1,last_col].min).each { |j| a << arr[i][j] unless i==r && j==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|
(1..3).each do |j|
puts "adjacent to #{arr[i][j]} at r=#{i}, c=#{j} = #{adjacent(arr, i, j)}"
end
end
in
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 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 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]
@Nick D: Tại sao loại bỏ các '2d' từ tiêu đề? –
@Ian P: Tôi đoán vì nó là thừa.'Hai chiều' là giống như '2D'. –