我正在尝试制作一个程序,通过递归执行八皇后,但我不断收到数组越界错误。我已经遇到这个问题有一段时间了,但我似乎无法真正找出问题所在。这是我的代码:
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");
}
}
}
最佳答案
第一个问题:
public void clearBoard()
{
for(int x = 0; x < BOARD_SIZE; x++) // changed from x <= BOARD_SIZE
{
for(int y = 0; y < BOARD_SIZE; y++) // changed from y <= BOARD_SIZE
{
board[x][y] = 0;
}
}
}
数组索引计数从0
开始到size-1
。 board[8][8]
中没有任何内容。
另一个问题
/* ... */
while(prevColumn >= 0)
{
prevRow = index(prevColumn);
for(int i = 0; i > BOARD_SIZE; i++) // i=0; i> BOARD_SIZE is always false, so no looping mechanism
{ /* ... */ }
更改为
for(int i = 0; i < BOARD_SIZE; i++) // corrected
另一个问题?
if(column > BOARD_SIZE) when `column = 8`
成功
if(column >= BOARD_SIZE)
另一个问题:
while(!queenPlaced && (row <= BOARD_SIZE))
成功
row < BOARD_SIZE
还有另一个吗?
queenPlaced = placeQueens(column + 1); // What if column = 7
关于java - 八皇后数组越界 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19024460/