Finding neighbours in a two-dimensional array

后端 未结 20 1223
忘了有多久
忘了有多久 2020-11-30 02:02

Is there an easy way of finding the neighbours (that is, the eight elements around an element) of an element in a two-dimensional array? Short of just subtracting and adding

20条回答
  •  不知归路
    2020-11-30 02:45

    I think Ben is correct in his approach, though I might reorder it, to possibly improve locality.

    array[i-1][j-1]
    array[i-1][j]
    array[i-1][j+1]
    
    array[i][j-1]
    array[i][j+1]
    
    array[i+1][j-1]
    array[i+1][j]
    array[i+1][j+1]
    

    One trick to avoid bounds checking issues, is to make the array dimensions 2 larger than needed. So, a little matrix like this

    3 1 4
    1 5 9
    2 6 5
    

    is actually implemented as

    0 0 0 0 0
    0 3 1 4 0
    0 1 5 9 0
    0 2 6 5 0
    0 0 0 0 0 
    

    then while summing, I can subscript from 1 to 3 in both dimensions, and the array references above are guaranteed to be valid, and have no effect on the final sum. I am assuming c, and zero based subscripts for the example

提交回复
热议问题