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
What constitutes a valid neighbor?
If all you want is to retrieve all the neighbors of a cell within the bounds of the array (including diagonals), this will suffice.
public List<Element> getNeighbors( int x, int y ) {
List<Element> neighbors = new ArrayList<>();
for( int i = -1; i <= 1; ++i ) {
for( int j = -1; j <= 1; ++j ) {
if( i == 0 && j == 0 ) {
continue;
}
if( i + x >= 0 && i + x < array.length &&
j + y >= 0 && j + y < array[0].length ) {
// we found a valid neighbor!
neighbors.add( array[i][j] );
}
}
}
return neighbors;
}