我在 java 中制作 NQueens 程序,但我无法检查对角线。现在,我只是以某种方式遍历数组,使其进入下一个对角线点,但在经历第一种可能性后,它让我超出了界限。有不同的方法可以做到这一点吗?我做错了吗?
这是给我数组越界异常的部分
private boolean checkLowerDiag(int row, int col)
{
if(col == 0)
{
return false;
}
else
{
for(int i = row, j = col; i < myNumsQueen && j >= 0; i++, j--)
{
if(myBoard[i+1][j-1] == true) // this line is the out of bounds
{
return true;
}
}
return false;
}
}
这是我的整个代码
package model;
public class NQueensModel
{
private int myNumsQueen;
public int myPossibilities=0;
private boolean[][] myBoard;
private static NQueensModel myModel = new NQueensModel(4);
public static void main (String[] args) {
System.out.println(myModel.solvePuzzle());
System.out.println(myModel.myPossibilities);
// System.out.println(myPossibilities);
}
public NQueensModel(int nQueens)
{
myNumsQueen = nQueens;
myPossibilities=0;
myBoard = new boolean[myNumsQueen][myNumsQueen];
}
public boolean solvePuzzle()
{
return this.solvePuzzle(0);
}
private boolean solvePuzzle(int ncolumn)
{
if(ncolumn>myNumsQueen-1)
{
myPossibilities++;
// return true;
}
int i;
for( i =0; i<myNumsQueen;i++)
{
if(this.isSafeMove(i, ncolumn)==true)
{
this.placeQueen(i,ncolumn);
System.out.println(i+ " " + ncolumn);
if(this.solvePuzzle(ncolumn+1)==true)
{
return true;
}
this.removeQueen(i, ncolumn);
System.out.println("remove: " + i+ " " + ncolumn);
}
}
return false;
}
private int solveCount(int count, int col)
{
for(int j = 0 ; j<col; j++){
if(myModel.solvePuzzle(j)==true){
count++;
}
else if(myModel.solvePuzzle(j)==false){
return count;
}
else
{
for(int i =0 ; i<col;i++){
count = solveCount(count, col+1);
}
return count;
}
return count;
}
return count;
}
private boolean isSafeMove(int row, int col)
{
if(this.checkLowerDiag(row, col)==true ||this.checkUpperDiag(row, col)==true ||this.checkLeft(row,col)==true)
{
return false;
}
else
{
return true;
}
}
private boolean checkUpperDiag(int row, int col)
{
if(row==0)
{
return false;
}
else
{
for(int i=row, j = col; i>=0 && j>=0; i--, j--)
{
if(myBoard[i][j]==true)
{
return true;
}
}
return false;
}
}
private boolean checkLowerDiag(int row, int col)
{
if(col==0 )
{
return false;
}
else
{
for(int i = row, j = col; i<myNumsQueen && j>=0; i++, j--)
{
if(myBoard[i+1][j-1]==true)
{
return true;
}
}
return false;
}
}
private boolean checkLeft(int row, int col)
{
if(col==0)
{
return false;
}
else
{
for(int i = col; i>=0; i--)
{
if(myBoard[row][i]==true)
{
return true;
}
}
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()
// {
//
// }
}