I'm facing some issues to find the neighbours in a matrix. I'm trying not to put a lot of if
statements in the code because I'm pretty sure there's a better way to do it but I don't know exactly how.
To simplify, let's say we have the following matrix:
1 2 3 4 5
6 7 8 9 6
1 2 3 4 5
2 3 4 6 7
Considering the cell [2,2] = 3
, the neighbours would be (i,j-1)
,(i-1,j)
,(i+1,j)
,(i,j+1)
,(i+1,j+1)
,(i-1,j-1)
. I created a "mask" for it using a for-loop
like this, where inicio[0]
is the i-coordinate of my current element (2 in the example) and inicio[1]
is the j-coordinate (also 2 for element 3). Also, I'm considering the element must be in the center of the mask.
for(k=inicio[0]-1;k<inicio[0]+1;k++){
for(z=inicio[1]-1;z<inicio[1]+1;z++)
if(k!=0 || z!=0) //jump the current cell
However, I don't know how to treat the elements in the borders. If I want to find the neighbours of element [0,0] = 1
for example, considering the element must be in the middle of the mask like this:
x x x
x 1 2
x 6 7
How can I treat those X
elements? I thought of initializing the borders on zero but I'm thinking this is not the proper way to do it. So if anyone can explain a better way to do it or an algorithm, I will be glad.