鉴于我试图在 Java 中实现的规模较小:
int[][] arr = new int[2][2]{
{ 1, 0 },
{ 0, 1 }
};
int[][] path = null;
Queue<int[][]> q = new LinkedList<int[][]>();
q.add(arr);
while(q.size() != 0) {
path = q.poll(); // pop the queue
for (int i=0; i<2; i++) {
for (int j=0; j<2; j++) {
if (path[i][j] == 0) {
path[i][j] = 1;
q.add(path);
path[i][j] = 0;
}
}
}
}
我通过 NetBeans 跟踪了 while 和 for 循环内每次迭代的 q 内容。然而,它们具有相同的值。
我期望在第一次 for 循环执行结束时会出现这样的情况:
{ {1 , 1} , {0 , 1} } and { {1 , 0} , {1 , 1} }
但相反,它们是:
{ {1 , 0} , {0 , 1} } and { {1 , 0} , {0 , 1} }
这是数组 path 的最后一个值,因为嵌套 for 循环的第一次执行已经结束。
我应该怎么做才能使我推送到 q 的那个不是对 path 数组的引用?
最佳答案
尝试添加 path
数组的副本。
for (int i=0; i<2; i++) {
for (int j=0; j<2; j++) {
if (path[i][j] == 0) {
path[i][j] = 1;
// here
int[][] copy = new int[2][2];
for(int k=0; k<2; k++) {
copy[k] = path[k].clone();
}
q.add(copy);
path[i][j] = 0; // now, this does not affect the added element
}
}
}
编辑:您无法克隆 path
变量,因为数组的第一级上存在引用。
关于Java 推送到队列引用或值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20400453/