繁体   English   中英

在二维数组中查找节点邻居

[英]Find node neighbors in 2d array

假设我有以下(n * n)数组:

1 2 3 4
5 6 7 8
9 a b c
d e f g

我想编写一个函数,查找给定节点的邻居节点。 例如,对于节点1,它将返回具有2、6和5的数组。对于节点“ a”,它将返回具有节点5、6、7,b,f,e,d和9的向量。顺序无关紧要。 我尝试仅使用if语句来完成此操作,但是这很快就变成了一场噩梦。

解决此问题的最佳方法是什么?

// assume (x,y) is position in array you want to get neighbours from
// assume 'array' is your array with x first and then y
// assume T is type of your array stuff

ArrayList<T> list = new ArrayList<T>();

for (int i = x - 1; i <= x + 1; i++) {
    for (int j = y - 1; j <= y + 1; j++) {
        // check if (i,j) is in array bounds
        if (i >= 0 && j >= 0 && i < array.length() && j < array[i].length()) {
            // the point isn't its own neighbour
            if (i != x && j != y)
                list.add(array[i][j]);
        }
    }
}
return list.toArray();

编辑:由于您的Array为n * n大,因此您不必使用array.length(),但这种方式将适用于所有类型的数组。

您可以使用for循环,假设(i,j)是元素的位置,mat是您的数组

mat[n][n]
int res[8];
int x = 0;
for (int k = i - 1 ; k < 2 ;k++)
    for(int t = j-1 ; j  <2 ;j++)
        if ((k > 0) && (t > 0) && (t<n) && (k < n))
            res[x++] = mat[k][t];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM