+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?

3/12/2019 12:33:42 AM

esQmo_

1 Answer

New 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.