获取二维数组中的相邻元素? [英] Get adjacent elements in a two-dimensional array?

查看:54
本文介绍了获取二维数组中的相邻元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组,比如说

I have a two-dimensional array, say

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]);
        }
    }
}

这篇关于获取二维数组中的相邻元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆