简体   繁体   中英

Find node neighbors in 2d array

Assume that I have the following (n * n) array:

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. I tried to do this with only using if-statements, but it turned into a nightmare really quick.

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.

you can use for loops, let assume that (i,j) is the location of your element, mat is your array

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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