Reputation: 11
I have been working on a 8-puzzle for class, and getting frustrated a bit checking out code. I need to write code regarding left, right, up, and down movement. When I remove the right, the code gives a "index out of bounds -1" error, for the double array, after expanding to get the successor nodes and adding them. Is the code below proper for going through the maze/successors, that returns the child to the parent? Is something wrong in the code for left, up, down, and right?
When I return several tests, I do see that the movement of the 0 moves to the right, and then down when it reaches the edge, so I am not sure if the code below is actually functioning correct, or if something in it needs to be changed.
The puzzle needs to give an output of:
1 2 3
4 5 6
7 8 0
Typical output shows:
1 7 8
5 4 2
3 6 0
As such, pathing seems to be wrong and I believe it is related to the movement code below, but I am unsure. The question I have is the code below accurate, does something need to be changed in it? Is something causing the ArrayIndexoutOfBounds -1 related to this, or is it something else?
ArrayList<Node> successors = new ArrayList<Node>();
//generate a successor from moving the 0 to the right
if (col < size-1) {
int[][] right = Board.copyBoard(board);
right[row][col] = right[row][col + 1];
right[row][col+1] = 0;
successors.add(new Node(right));
} else if (col < size - 1) {
int[][] left = Board.copyBoard(board);
left[row][col] = left[row][col-1];
left[row][col-1] = 0;
successors.add(new Node(left));
} else if (row < size-1) {
int[][] down = Board.copyBoard(board);
down[row][col] = down[row + 1][col];
down[row + 1][col] = 0;
successors.add(new Node(down));
} else if (row < size - 1) {
int[][] up = Board.copyBoard(board);
up[row][col] = up[row-1][col];
up[row-1][col] = 0;
successors.add(new Node(up));
}
return successors;
Upvotes: 1
Views: 428
Reputation: 613
At the moment, your code checks col < size -1 for both left and right movements, and similarly for up and down. The second condition should be col > 0 and the last one row >0
Upvotes: 3