For cell at location (i,j)
, i.e. i row, j column, coordinates of all its eight neighbors are
(i-1,j-1) | (i-1,j) | (i-1,j+1)
----------+---------+----------
(i, j-1) | (i ,j) | (i ,j+1)
----------+---------+----------
(i+1,j-1) | (i+1,j) | (i+1,j+1)
In a two-dimensional array array[row][col]
, you could access them by array[i][j]
. Of course, you need to make sure every coordinates are valid before you try to access cell at that coordinate, you can using the following condition to make this check:
// for coordinate (i, j) in array[row][col]
if ((0 <= i) && (i < row) && (0 <= j) && (j < col)) {
/* access array[i][j] */
}