此代码适用于 5x5、6x6、7x7,但在 8x8 中内存不足。我将内存增加到2048M,但它仍然不起作用。代码应该使用 Stack 类和回溯作为解决方案的一部分这是代码:
private int counter=0;
private boolean grid[][]=new boolean [ROWS][COLS];
private Stack tour=new Stack(0,0);
private int spaces=ROWS*COLS;
private int[][] intGrid=new int[ROWS][COLS];
private static final Point[] Moves=new Point[]{
new Point(-1, -2),
new Point(-1, 2),
new Point(1, -2),
new Point(1, 2),
new Point(-2, -1),
new Point(-2, 1),
new Point(2, -1),
new Point(2, 1),
};
public void run(){
fillIntGrid();
tourFrom(tour.first);
println("SOLUTION FOUND:");
printBoard();
}
public boolean tourFrom(Point currPoint){
counter++;
grid[currPoint.xCoord][currPoint.yCoord] = true;
intGrid[currPoint.xCoord][currPoint.yCoord]=counter;
if(counter==spaces)
return true;
for(Point nextMove:Moves){
int nextRow=currPoint.xCoord+nextMove.xCoord;
int nextCol =currPoint.yCoord+nextMove.yCoord;
tour.push(nextRow,nextCol);
if(nextRow<0 || nextRow>=grid.length)
continue;
else if(nextCol<0 || nextCol>=grid.length)
continue;
else if(grid[nextRow][nextCol])
continue;
if(tourFrom(tour.first))
return true;
}
grid[currPoint.xCoord][currPoint.yCoord] = false;
intGrid[currPoint.xCoord][currPoint.yCoord]=0;
counter--;
tour.pop();
return false;
}
public void fillIntGrid(){
for(int i=0;i<ROWS;i++){
for (int j=0;j<COLS;j++){
intGrid[i][j]=0;
}
}
}
可能的问题是什么?