Finding neighbours in a two-dimensional array

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

    an alternative to @SebaGR, if your language supports this:

    var deltas = { {x=-1, y=-1}, {x=0, y=-1}, {x=1, y=-1},
                   {x=-1, y=0},               {x=1, y=0},
                   {x=-1, y=1},  {x=0, y=1},  {x=1, y=1} };
    foreach (var delta in deltas)
    {
        if (x+delta.x < 0 || x + delta.x >= array.GetLength(0) ||
            y+delta.y < 0 || y + delta.y >= array.GetLength(1))
            continue;
    
        Console.WriteLine("{0}", array[x + delta.x, y + delta.y]);
    }
    

    Slight advantage in readability, possible performance if you can statically allocate the deltas.

提交回复
热议问题