+ 2

Finding neighbor of a point

How do I find neighbor of a point on a 2D grid? A point is given by e.g gameBoard[x][y], how to check it neighbor in 8 directions?

12th Mar 2019, 12:33 AM
esQmo_
esQmo_ - avatar
1 Odpowiedź
+ 4
For immediate neighbours, you just need to modify the indexes to retrieve the following elements: gameBoard[x][y-1], gameBoard[x+1][y-1], gameBoard[x+1][y] gameBoard[x+1][y+1] gameBoard[x][y+1] gameBoard[x-1][y+1] gameBoard[x-1][y] gameBoard[x-1][y-1] The indexes of some of these cells may become negative on the boundary or at the corners, and so you need to use conditional statements to check if you can actually retrieve the element or not for the given element, gameBoard[x][y]. Something like: if(y>0) { /* do something with gameBoard[x][y-1]; */ } if(x<gameBoard.length-1&&y>0) { /* do something with gameBoard[x+1][y-1] */ } ... if(x<gameBoard.length-1&&y<gameBoard[0].length-1) { /* do something with gameBoard[x+1][y+1] */ } and so on.
12th Mar 2019, 1:02 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar