我正在使用java并且正在尝试使用递归来编写一个解决NQueens难题的程序。问题是当它不应该是真的给我时(例如3应该返回false,因为你可以NQueen一个3x3网格)。我已经多次查看了所有内容,但我无法找到出错的地方。有人有任何想法吗?
package model;
public class NQueensModel
{
private int myNumsQueen;
private boolean[][] myBoard;
private static NQueensModel myModel = new NQueensModel(3);
public static void main (String[] args) {
System.out.println(myModel.solvePuzzle());
}
public NQueensModel(int nQueens)
{
myNumsQueen = nQueens;
myBoard = new boolean[myNumsQueen][myNumsQueen];
}
public boolean solvePuzzle()
{
return this.solvePuzzle(myNumsQueen);
}
private boolean solvePuzzle(int ncolumn)
{
if(ncolumn>myNumsQueen)
{
return true;
}
int i;
for( i =0; i<myBoard.length;i++)
{
if(this.isSafeMove(i, ncolumn)==true)
{
myBoard[i][ncolumn-1]=true;
if(this.solvePuzzle(ncolumn+1)==true)
{
return true;
}
myBoard[i][ncolumn]=false;
}
}
return false;
}
private boolean isSafeMove(int row, int col)
{
for(int i=0; i<myBoard[row].length; i++)
{
if(myBoard[row][i]==true)
{
return false;
}
}
for(int i = 0; i<myBoard.length; i++)
{
if(myBoard[i][col-1]==true)
{
return false;
}
}
if(this.checkLowerDiag(row, col)==true)
{
return false;
}
if(this.checkUpperDiag(row, col)==true)
{
return false;
}
if(this.checkLeft(row,col)==true)
{
return false;
}
else
{
return true;
}
}
private boolean checkUpperDiag(int row, int col)
{
if(row==0)
{
return true;
}
else if(col==myBoard[0].length)
{
if (myBoard[row-1][col-2]==true)
{
return true;
}
else
{
return false;
}
}
else if(myBoard[row-1][col-2]==true || myBoard[row-1][col]==true)
{
return true;
}
else
{
return false;
}
}
private boolean checkLowerDiag(int row, int col)
{
if(col==1 && myBoard[row][col]==true)
{
return true;
}
else if(col == myBoard[0].length)
{
if(myBoard[row+1][col-2]==true)
{
return true;
}
else
{
return false;
}
}
else if(row == myBoard.length)
{
return true;
}
else if(myBoard[row+1][col-2]==true || myBoard[row+1][col]==true)
{
return true;
}
else
{
return false;
}
}
private boolean checkLeft(int row, int col)
{
if(myBoard[row][col-1]==true)
{
return true;
}
else
{
return false;
}
}
private boolean placeQueen(int row, int col)
{
myBoard[row][col] = true;
return true;
}
private boolean removeQueen(int row, int col)
{
myBoard[row][col] = false;
return false;
}
// public String toString()
// {
//
// }
}