Given a grid, how to access all 8 adjacent blocks in short code?

I have a 2d array. Let my current position be pos = (x,y). I need to access all 8 adjacent blocks of this grid, namely ( [x-1,y-1], [x-1,y], [x-1, y+1], [x,y-1], [x,y+1], [x+1,y-1] ,[x+1,y], [x+1,y+1] ) and then I should update my answer given some condition is fulfilled in those blocks. I can do it with 8 if else conditions. But is there faster way?

no bro. it is fastest.

1 Like

there is no faster way but there is a shorter way
make dx and dy arrays
eg: for 4 directions
dx=[0,0,1,-1]
dy=[1,-1,0,0]
for(i=0;i<4;i++)
{
x1=x+dx[i];
y1=y+dy[i];
//do something with (x1,y1)
}

1 Like