Eddy Freeman
Eddy Freeman

Reputation: 3309

Solving NxN puzzle In 2-dimensional array

I am solving a NxN puzzle in Java 2D array (int state[][]) and I am stuck.

I am using the Manhattan distance heuristic. The problem I have now is how to code the successors of a node. I have seen numerous examples on the net how a node's successors (neighbours) are generated but they are all in 1 dimensional array. I can't find any tutorial that teaches generating the successors of a node in 2D arrays.

How can I code to generate the successors of a node? A node can move to the empty space to the LEFT, RIGHT, DOWN or UP. The size of the board is NxN.

It is my first time using 2D arrays to program game like these puzzles.

Upvotes: 0

Views: 1905

Answers (1)

perreal
perreal

Reputation: 98118

Probably the code you have defines

UP as ( i + width * (j-1))
DOWN as ( i + width * (j+1))
LEFT as ( i - 1 + width * j)
RIGHT as (i + 1 + width *j)

You need to define these as (i, j-1), (i, j+1), (i-1, j), (i+1, j) respectively.

Edit:

In a 1D array, you need to flatten the element index. If the element is at column i, row j, flat address would be ( j*width [meaning skip j rows] + i [meaning skip i items in this row]). If you have a 2D array then you can simple use array[i][j] instead of a flat address.

Upvotes: 1

Related Questions