简体   繁体   English

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

[英]Find node neighbors in 2d array

Assume that I have the following (n * n) array: 假设我有以下(n * n)数组:

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

I want to write a function that finds the neighbor nodes of a given node. 我想编写一个函数,查找给定节点的邻居节点。 For example, for node 1, it will return an array with 2, 6, and 5. For node "a", it will return a vector with node 5, 6, 7, b, f, e, d, and 9. The order does not matter. 例如,对于节点1,它将返回具有2、6和5的数组。对于节点“ a”,它将返回具有节点5、6、7,b,f,e,d和9的向量。顺序无关紧要。 I tried to do this with only using if-statements, but it turned into a nightmare really quick. 我尝试仅使用if语句来完成此操作,但是这很快就变成了一场噩梦。

Whats the best way to approach this problem? 解决此问题的最佳方法是什么?

// 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();

EDIT: As your Array is n*n big you don't have to use array.length(), but this way it will work for all kind of array. 编辑:由于您的Array为n * n大,因此您不必使用array.length(),但这种方式将适用于所有类型的数组。

you can use for loops, let assume that (i,j) is the location of your element, mat is your array 您可以使用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