我正在尝试制作一个使用递归执行八皇后的程序,但我不断收到数组越界错误。我已经有一段时间遇到这个问题了,我似乎无法确定问题所在。这是我的代码:
public class Queens {
public int currColumn = 0;
public static final int BOARD_SIZE = 8;
public static final int EMPTY = 0;
public static final int QUEEN = 1;
private int board[][];
public Queens() {
board = new int[BOARD_SIZE][BOARD_SIZE];
}
public void clearBoard() {
for (int x = 0; x <= BOARD_SIZE; x++) {
for (int y = 0; y <= BOARD_SIZE; y++) {
board[x][y] = 0;
}
}
}
public void displayBoard() {
for (int x = 0; x < BOARD_SIZE; x++) {
System.out.print("\n");
for (int y = 0; y < BOARD_SIZE; y++) {
System.out.print(board[x][y]);
}
}
}
public boolean placeQueens(int column) {
if (column > BOARD_SIZE) {
return true;
} else {
boolean queenPlaced = false;
int row = 1;
while (!queenPlaced && (row <= BOARD_SIZE)) {
if (isUnderAttack(row, column)) {
++row;
} else {
setQueen(row, column);
queenPlaced = placeQueens(column + 1);
if (!queenPlaced) {
removeQueen(row, column);
++row;
}
}
}
return queenPlaced;
}
}
public void setQueen(int row, int column) //SET BACK TO PRIVATE
{
board[row][column] = 1;
}
private void removeQueen(int row, int column) {
board[row][column] = 0;
}
private boolean isUnderAttack(int row, int column) {
if (column == 0) {
return false;
}
int prevColumn = column - 1;
int prevRow = index(prevColumn);
while (prevColumn >= 0) {
prevRow = index(prevColumn);
for (int i = 0; i > BOARD_SIZE; i++) {
if (prevRow == row && prevColumn + i == column) //Going right
{
return true;
}
if (prevRow + i == row && prevColumn + i == column) //Going up/right
{
return true;
}
if (prevRow - i == row && prevColumn + i == column) //Going down/right
{
return true;
}
}
prevColumn--;
}
return false;
}
public int index(int column) //BACK TO PRIVATE
{
for (int i = 0; i < 8; i++) {
if (board[i][column] == 1) {
return i;
}
}
return 0;
}
public static void main(String[] args) {
Queens x = new Queens();
if (x.placeQueens(1) == true) {
x.displayBoard();
} else {
System.out.println("No solution found");
}
}
}