Ares91
Ares91

Reputation: 526

Find the neighbours in a 2D array with repeat strategy

Exist a simple and compact way (non recursive) to find all neighbours at a distance D from a given coordinate inside a 2D array with height H and width W using a repeat strategy.

enter image description here

For example in the image above we have a 2D array/matrix with height and width 3. Now what Im trying to archive is to get the neighbours of element 2 with distance/hop 1 which in this case are 7,8,6,1,2,0,4,5,3 (circled in red) using a repeat strategy(p.s without creating a bigger matrix with 9 small matrixes).

Does anyone know a way/algorithm of how to get this thx

enter image description here

Upvotes: 1

Views: 1767

Answers (1)

Krishna Choudhary
Krishna Choudhary

Reputation: 625

As per my understanding of the question ,this can be achieved by nested loops.

Assuming that you have 'x' and 'y' coordinates for the target value, hop as 'h'.

Assuming array size to be m X n

Then make two loops:

  Outer loop 'i' from x-h to x+h

    Inner loop 'j' from y-h to y+h

        Elements arr[i%m][j%n] are your neighbors

UPDATE: I have updated the code as per my understanding of the problem. This way, u can go upto 'hop' steps, and also u will not get 'ArrayIndexOutOfBoundException'.

Upvotes: 1

Related Questions