好的,所以我正在研究一个使用深度优先搜索解决游戏的程序(这是作业作业的一部分)。我在2D char数组中存储游戏板。因此,我创建了一个堆栈来存储各种电路板状态:
private Stack<char[][]> open = new Stack();
我有以下两种方法:
public void dfsearch() {
open.push(this.board);
while (!open.isEmpty()) {
char[][] state = open.pop();
System.out.println("Popped " + Arrays.deepToString(state) + " from stack");
if (goal(state)) {
System.out.println("Goal!");
break;
}
if (!visited(state)) {
generateChildren(state);
visited.add(state);
}
}
}
private void generateChildren(char[][] state) {
for (int i=0; i<state.length; i++) {
for (int j=0; j<state.length; j++) {
char[][] tmp = new char[N][N];
System.arraycopy(state, 0, tmp, 0, state.length);
touch(tmp, i, j);
System.out.println("Pushing " + Arrays.deepToString(tmp) + " to stack");
open.push(tmp);
System.out.println("Peeking " + Arrays.deepToString(open.peek()) + " from stack");
}
}
}
正如你所看到的,dfsearch()方法是我正在进行深度优先搜索的地方,而generateChildren()方法是我生成要搜索的子节点的地方。
这是我的问题:数组未正确推送到堆栈。为了说明我的意思,我添加了一些打印语句来打印从堆栈中推送和弹出的内容。在我的generateChildren()方法中,它输出以下内容:
Pushing [[R, R, R], [R, D, D], [D, D, D]] to stack
Pushing [[E, E, E], [R, R, D], [D, D, D]] to stack
Pushing [[E, D, D], [R, R, R], [D, D, D]] to stack
Pushing [[D, D, D], [E, E, R], [R, D, D]] to stack
Pushing [[D, R, D], [D, D, E], [R, R, D]] to stack
Pushing [[D, R, R], [D, R, D], [R, R, R]] to stack
Pushing [[D, R, R], [R, R, D], [E, E, R]] to stack
Pushing [[D, R, R], [R, E, D], [D, D, E]] to stack
Pushing [[D, R, R], [R, E, R], [D, R, D]] to stack
为了验证推送到堆栈的内容,我还添加了一个打印方法来打印堆栈中偷看的结果,结果如下:
Peeking [[R, R, R], [R, D, D], [D, D, D]] from stack
Peeking [[E, E, E], [R, R, D], [D, D, D]] from stack
Peeking [[E, D, D], [R, R, R], [D, D, D]] from stack
Peeking [[D, D, D], [E, E, R], [R, D, D]] from stack
Peeking [[D, R, D], [D, D, E], [R, R, D]] from stack
Peeking [[D, R, R], [D, R, D], [R, R, R]] from stack
Peeking [[D, R, R], [R, R, D], [E, E, R]] from stack
Peeking [[D, R, R], [R, E, D], [D, D, E]] from stack
Peeking [[D, R, R], [R, E, R], [D, R, D]] from stack
到目前为止这么好,对吗?好吧,当我在dfsearch()方法中从堆栈中弹出结果时,我得到以下内容:
Popped [[D, R, R], [R, E, R], [D, R, D]] from stack
Popped [[D, R, R], [R, E, R], [D, R, D]] from stack
Popped [[D, R, R], [R, E, R], [D, R, D]] from stack
Popped [[D, R, R], [R, E, R], [D, R, D]] from stack
Popped [[D, R, R], [R, E, R], [D, R, D]] from stack
Popped [[D, R, R], [R, E, R], [D, R, D]] from stack
Popped [[D, R, R], [R, E, R], [D, R, D]] from stack
Popped [[D, R, R], [R, E, R], [D, R, D]] from stack
Popped [[D, R, R], [R, E, R], [D, R, D]] from stack
如您所见,从堆栈弹出的所有数组都等于在generateChildren()方法中推送到堆栈的最后一个数组。
希望你能够遵循这一点。我的问题是,我做错了什么?
提前致谢!
答案 0 :(得分:0)
对于任何偶然发现这一点的人来说,事实证明我的问题实际上非常简单。我正在使用System.arraycopy来复制我的数组。我没有考虑到这不会做深层复制的事实,因此它引起了问题。