Finding neighbor of a point | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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 Answer
+ 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
Kinshuk Vasisht
Kinshuk Vasisht - avatar