获得在一个二维阵列相邻的元素?阵列、元素

2023-09-11 22:57:25 作者:眉目亦如画

我有一个二维数组,说

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

和我需要得到所有相邻的编号,1(2,3,4,5,6,7,8,9)

And i need to get all the numbers adjacent to 1(2, 3, 4, 5, 6, 7, 8, 9)

有一个不太难看的解决方案比:

Is there a less ugly solution than:

topLeft = array[x-1][y-1]
top  = array[x][y-1]
topRight = array[x+1][y-1]
# etc

谢谢!

推荐答案

如果你不担心顺序,最干净的可能是使用了几个循环的:

If you're not worried about the order, the cleanest is probably to use a couple of loops:

result = new List<int>(8);
for (dx = -1; dx <= 1; ++dx) {
    for (dy = -1; dy <= 1; ++dy) {
        if (dx != 0 || dy != 0) {
            result.Add(array[x + dx][y + dy]);
        }
    }
}

如果顺序很重要,你可以构造的所有(DX,DY)的列表中,你想要的顺序和迭代的吧。

If the order is important, you can construct a list of all the (dx, dy) in the order you want and iterate over that instead.

正如在评论中,你可能要添加边界检查。你可以做这样的(假设顺序并不重要):

As pointed out in the comments, you probably want to add boundary checks. You could do that like this (assuming order doesn't matter):

List<int> result = new List<int>(8);
for (int dx = (x > 0 ? -1 : 0); dx <= (x < max_x ? 1 : 0); ++dx)
{
    for (int dy = (y > 0 ? -1 : 0); dy <= (y < max_y ? 1 : 0); ++dy)
    {
        if (dx != 0 || dy != 0)
        {
            result.Add(array[x + dx][y + dy]);
        }
    }
}
 
精彩推荐
图片推荐