There's often (if not always) a sacrifice in term of speed vs. memory; I had to implement a Sudoku solver some time ago in Java, and it was faster to assign each cell a list of cell groups. So, instead of checking boundaries every time, I simply had to iterate over each group, then each cell within each groups. The check was made once to create the groups.
Something like :
class Neighbors {
ArrayList<Point> pList = new ArrayList<Point>();
}
...
int[][] grid = new int[10][10];
Neighbors[][] n = new Neighbors[10][10];
for (int x=0; x<10; x++) {
for (int y=0; y<10; y++) {
grid[x][y] = (y*10)+x; // 0..99
n[x][y] = new Neighbors();
for (int nx=x-1; nx<=x+1; nx++) {
for (int ny=y-1; ny<=y+1; ny++) {
if (!(x==nx && y==ny) && nx>=0 && ny>=0 && nx<10 && ny<10) {
n[x][y].pList.add(new Point(nx,ny)); // add valid neighbor
}
}
}
}
}
then, for any given point : x, y
for (Point p : n[x][y].pList) {
// grid[p.x][p.y] is a neighbor of grid[x][y]
}
Well, my solution was a little more sophisticated, but the principle is the same. If your grid is a 2-dimension array of objects, the neighbors can actually be the object at grid[nx][ny]
instead of points for direct object access.
You will eventually need to check for x>=0
, y>=0
, x<SIZE_W
, and y<SIZE_H
, but this solution does the check only onece, so it is in my opinion quite efficient when querying neighbors often for each grid cell. If you need to resize the grid often, then this solution would need to be adapted.
Another approach would be to pad your array in each direction with ignored
flag value (such as null, -1, etc.) and simply do a normal check ignoring such cells :
int pad_size = 1; // how many neighbors around x,y
int size_w = 10+(pad_size*2);
int size_h = 10+(pad_size*2);
int[][] grid = new int[size_w][size_h];
for (int x=0; x<size_w; x++) {
for (int y=0; y<size_h; y++) {
if (x<pad_size || x>=size_w-pad_size || y<pad_size || y>=size_h-pad_size) {
grid[x][y] = -1; // ignore
} else {
grid[x][y] = ((y-pad_size)*10)+(x-pad-size); // 0..99
}
}
}
then for any given point : x,y
for (int nx=x-pad_size; nx<=x+pad_size; nx++) {
for (int ny=y-pad_size; ny<=y+pad_size; ny++) {
if (-1!=grid[nx][ny] && !(nx==x && ny==y)) {
// grid[p.x][p.y] is a neighbor of grid[x][y]
}
}
}