有人可以给我关于我的 java 程序的提示或指导吗?我坚持回溯的想法。这是代码。如果你看一下方法solve(),它会递归地调用自己,但是我被困在它无法放置更多皇后并试图回溯的地方。
public NQueens(int N)
{
this.N = N;
board = new boolean[N][N];
solved = solve(N);
if(solved == true)
{
System.out.println(N+"x"+N+" solution:");
printBoard(N);
}
else
{
System.out.println("There is no solution for "+N+"x"+N+" board");
}
}
public boolean solve(int waitingQueens)
{
if(waitingQueens == 0) return true;
for(int row = 0; row < N; row++)
{
for(int column = 0 ; column < N ; column++)
{
if(isValid(row, column))
{
board[row][column] = true;
waitingQueens--;
boolean solved = solve(waitingQueens);
if(!solved)
{
board[row][column] = false;
solved = solve(waitingQueens);
}
return solved;
}
}
}
return false;
}
public boolean isValid(int rowParam, int columnParam)
{
for(int x = 0; x < N; x++)
{
for(int y = 0; y < N; y++)
{
if(board[x][y] == true) //find the already placed queens on the board and check if the queen about to be placed is on a valid position
{
if(x == rowParam) //check the validity of the row
return false;
if(y == columnParam) //check the validity of the column
return false;
if(Math.abs(x-rowParam) == Math.abs(y-columnParam)) //check the validity of the diagonals
return false;
}
}
}
return true;
}
public void printBoard(int printParam)
{
for(int x1 = 0; x1 < printParam; x1++)
{
for(int y1 = 0; y1 < printParam; y1++)
{
if(board[x1][y1] == true)
{
System.out.print("Q ");
}
else{
System.out.print("* ");
}
}
System.out.println();
}
System.out.println();
}