由网友(6.萌了一个春)分享简介:所以,我有一个4×4的二维数组(它将永远是这些尺寸)。与阵列上的位置,一些行和列的开始,我想找到它的所有有效的邻居。到目前为止,我有一个很笨重的实现。So, I have a 4x4 2D array (it will always be these dimensions). Starting with a loca...
所以,我有一个4×4的二维数组(它将永远是这些尺寸)。与阵列上的位置,一些行和列的开始,我想找到它的所有有效的邻居。到目前为止,我有一个很笨重的实现。
So, I have a 4x4 2D array (it will always be these dimensions). Starting with a location on the array, some row and column, I want to find all of its valid neighbors. So far, I have a really clunky implementation.
//add row
if ( !((row + 1) > 3)) {
//do stuff
}
//sub row
if ( !((row - 1) < 0)) {
//do stuff
}
//add col
if ( !((col + 1) > 3)) {
//do stuff
}
//sub col
if ( !((col - 1) < 0)) {
//do stuff
}
... and so on
这是残酷的。我觉得我并不需要检查每一个邻居,当我开始通过了解元素的位置。任何想法?
This is brutal. I feel like I do not need to check every single neighbor when I start by knowing the location of the element. Any ideas?
推荐答案
下面是我会怎么做:那得到的x,y对的有效邻居列表的方法,给出一个任意 [ X,Y]
点与广义任何数组大小为:
Here's how I'd do it: a method that gets a list of x,y pairs for valid neighbors, given an arbitrary [x,y]
point and generalized to any array size:
public List<int[]> getNeighbors(x, y, maxX, maxY) {
neighbors = new ArrayList<int[]>;
if x > 0:
neighbors.add({x-1, y});
if y > 0:
neighbors.add({x, y-1});
if x < maxX:
neighbors.add({x+1, y});
if x < maxY:
neighbors.add({x, y+1});
return neighbors;
}
[...]
for (int[] coords : getNeighbors(x, y, 4, 4)) {
// do stuff
}
相关推荐
最新文章