簡體   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