Suppose you are in cell (i, j)
. Then, on an infinite grid, your neighbors should be [(i-1, j-1), (i-1,j), (i-1, j+1), (i, j-1), (i, j+1), (i+1, j-1), (i+1, j), (i+1, j+1)]
.
However, since the grid is finite some of the above values will get outside the bounds. But we know modular arithmetic: 4 % 3 = 1
and -1 % 3 = 2
. So, if the grid is of size n, m
you only need to apply %n, %m
on the above list to get the proper list of neighbors: [((i-1) % n, (j-1) % m), ((i-1) % n,j), ((i-1) % n, (j+1) % m), (i, (j-1) % m), (i, (j+1) % m), ((i+1) % n, (j-1) % m), ((i+1) % n, j), ((i+1) % n, (j+1) % m)]
That works if your coordinates are between 0
and n
and between 0
and m
. If you start with 1
then you need to tweak the above by doing a -1
and a +1
somewhere.
For your case n=m=4
and (i, j) = (0, 0)
. The first list is [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
. Applying the modulus operations you get to [(3, 3), (3, 0), (3, 1), (0, 3), (0, 1), (1, 3), (1, 0), (1, 1)]
which are exactly the squares marked [n]
in your picture.