Finding neighbours in a two-dimensional array

后端 未结 20 1187
忘了有多久
忘了有多久 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条回答
  •  Happy的楠姐
    2020-11-30 02:42

    The approach I usually take is described on the bottom of this blog: https://royvanrijn.com/blog/2019/01/longest-path/

    Instead of hardcoding the directions or having two nested loops I like to use a single integer loop for the 8 ‘directions’ and use (i % 3)-1 and (i / 3)-1; do check out the blog with images.

    It doesn’t nest as deep and is easily written, not a lot of code needed!

提交回复
热议问题