简体   繁体   English

8-Puzzle Java算法拼图

[英]8-Puzzle Java Algorithm Puzzle

I have been working on a 8-puzzle for class, and getting frustrated a bit checking out code. 我一直在为课堂制作一个8拼图,并且在检查代码时感到沮丧。 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. 当我删除右边时,代码为double数组提供了“index out of bounds -1”错误,扩展后获取后继节点并添加它们。 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. 当我返回几个测试时,我确实看到0的移动向右移动,然后当它到达边缘时向下移动,所以我不确定下面的代码是否实际上正常运行,或者它是否需要改变了。

The puzzle needs to give an output of: 这个谜题需要输出:

1 2 3 1 2 3

4 5 6 4 5 6

7 8 0 7 8 0

Typical output shows: 典型输出显示:

1 7 8 1 7 8

5 4 2 5 4 2

3 6 0 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? 导致ArrayIndexoutOfBounds -1与此相关的东西,还是其他东西?

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;

At the moment, your code checks col < size -1 for both left and right movements, and similarly for up and down. 目前,您的代码检查col <size -1是否为左右移动,以及类似的上下移动。 The second condition should be col > 0 and the last one row >0 第二个条件应为col> 0,最后一行> 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM