0

I am trying to calculate valid neighbour of a node

Array contains elements like [2,8,3,0,1,4,7,6,5]

Matrix:

          2 8 3
          0 1 4
          7 6 5

It's similar to 8 puzzle logic. In the above matrix, i can swap 0 with 2 or 1 or 7. i tried with -1,+1,-3,+3. But 0 can't be swapped with 3. so i can't use -1 or +1. Also i need to update the position in array. What is the logic to achieve this.

iPhone Guy
  • 1,285
  • 3
  • 23
  • 34

2 Answers2

0

Since it's only 3x3 you can hardcode the neighbour-list (if it was more complicated I would suggest writing a logic that computes it):

neighbour-map := {0:[1,3], 1:[0,2,4], 2:[1,4,5],...}

0:[1,3] means that the first item in the array (value=2) has neighbours on the indexes: 1,3 (values: 8 and 0). etc.

If you need to deal with a larger "matrix", then you should compute the neighbors. It'll be easier for you to move the input into a matrix (array of arrays) and then calculate it according to the list of "rules" that ak0053792 wrote below - but also handle all the "corner" cases (items that are on the upper-most line don't have a neighbor at y-1 for example).

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

Simple logic would be check if the array element from which we are swapping selected element is neighbouring element. This could be done by below algorithm

1) Locate the position of current element

2) Locate the position of the element from which swapping is done.

3) Check if the position of swapping element lies in range below from current element, so if the position of current element is x,y then swapping element must lie in :

1) x-1, y-1
2) x-1, y
3) x-1, y+1
4) x, y-1
5) x, y+1
6) x+1, y+1
7) x+1, y
8) x+1, y-1
ak0053792
  • 523
  • 1
  • 5
  • 18