I'm trying to add all adjacent fields (including diagonally adjacent) of each field in an nxm integer matrix. When looping through this index by index, then at the border and corner cases (e.g. [0][n-1]), this evaluation will fails as some of the surrounding eight fields will not exist (in the above example specifically [-1][n-2], [-1][n-1], [-1][n], [0][n] and [1][n]).
The simplest solutions that come to my mind are either going
if(i != 0){
//check all fields
}else if(i == 0 && j == 0){
//check only fields left, below and left-below
}else if(...){
...
}
or using try-catch eight times
int count = 0;
try{
count = matrix[i-1][j];
}catch(IndexOutOfBoundsException e){
....
}
which still looks ugly. Is there a better solution for this?
CodePudding user response:
You can use a nested loop to generate all the possible moves, so the bounds check only has to be written once.
int count = 0;
for (int dx = -1; dx <= 1; dx )
for (int dy = -1; dy <= 1; dy )
if (dx != 0 || dy != 0) {
int nx = i dx, ny = j dy;
if (nx >= 0 && nx < n && ny >= 0 && ny < m) count = matrix[nx][ny];
}
CodePudding user response:
You can create matrix of size n 2 x m 2. this matrix will have extra rows and columns surrounding the nxm matrix. now you fill these surrounding rows/columns with zeros. now if you make your loops start at 1 and going until size()-2 you will always have surrounding cells