我在生成爬山算法时难以生成邻居。
这是我目前正在使用的代码。
public ArrayList<Board> generateNeighbors(){
ArrayList<Board> neighborBoards = new ArrayList<Board>();
HashMap<Integer, Integer> initialQueenLocations = this.queenLocations;
for(int i = 0; i < queen; i++){
int[][] neighborBoard = new int[queen][queen];
HashMap<Integer, Integer> neighborQueenLocations = initialQueenLocations;
for(int k = i; k < queen; k++){
for(int j = 0; j < queen; j++){
neighborBoard[j][initialQueenLocations.get(j)] = 1;
}
int initialLocation = initialQueenLocations.get(k);
if(initialLocation > 0){
neighborBoard[k][initialLocation] = 0;
neighborBoard[k][initialLocation - 1] = 1;
neighborQueenLocations.put(k, initialLocation - 1);
neighborBoards.add(new Board(neighborBoard, neighborQueenLocations));
break;
}
}
}
}
我遇到的问题是我生成的每个新电路板都保存了最后一步,我希望每个相邻电路板的步长为1。这是(错误的)输出:
//initial
0|0|1|
0|1|0|
0|1|0|
//step 1
0|1|0|
0|1|0|
0|1|0|
//step 2
0|1|0|
1|0|0|
0|1|0|
//step 3
0|1|0|
1|0|0|
1|0|0|
这是我想要的输出。
//initial
0|0|1|
0|1|0|
0|1|0|
//step 1
0|1|0|
0|1|0|
0|1|0|
//step 2
0|0|1|
1|0|0|
0|1|0|
//step 3
0|0|1|
0|1|0|
1|0|0|
正如您所看到的,它正在保存上一步的移动。有人可以帮忙吗?
答案 0 :(得分:1)
您的问题是您在初始HashMap
中覆盖了您的值。如果您将neighborQueenLocations
设置为initialQueenLocations
,则基本上只需设置对initialQueenLocations
HashMap的引用。因此当您执行neighborQueenLocations.put(k, initialLocation - 1);
时,您会写入initialQueenLocations
保留的内存,但通过neighborQueenLocations
变量“访问”它。
...
for(int i = 0; i < queen; i++){
int[][] neighborBoard = new int[queen][queen];
// Here you are setting a reference, not copying the values
HashMap<Integer, Integer> neighborQueenLocations = initialQueenLocations;
...
稍后在您的代码中,您将覆盖initialQueenLocations
HashMap中的值,因为neighborQueenLocations
只是对initialQueenLocations
的引用。
...
neighborBoard[k][initialLocation] = 0;
neighborBoard[k][initialLocation - 1] = 1;
neighborQueenLocations.put(k, initialLocation - 1);
...
这就是为什么它“记住”采取的最后一步。