Finding neighbours in a two-dimensional array

后端 未结 20 1194
忘了有多久
忘了有多久 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:37

    array[i][j] has neighbors

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

    That's probably the fastest/easiest way is to just list all possible neighbors. Make sure to do index out of bound checking though.

    Some languages might offer a shortcut way of doing this, but I don't know of any.

提交回复
热议问题