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
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 getNeighbors(x, y, maxX, maxY) {
neighbors = new ArrayList;
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
}