One of my homework assignments is to solve the eight-crown problem using a two-dimensional array to represent the board. I keep getting the index beyond error: 8 in my isUnderAttack method at:
if (board[row][j] == QUEEN)
and in my "placeQueen" method:
if (isUnderAttack(row, column)) {
and
queenPlaced = placeQueens(column+1);
Where could I be wrong? I would add more tags to this post, but I am a new user and I cannot create "new tags". Excuse me!
Here is what I created:
public class Queens {
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 i = 0; i < BOARD_SIZE; i++){
for (int j = 0; j <BOARD_SIZE; j++){
board[i][j] = EMPTY;
}
}
}
public void displayBoard() {
for (int i = 0; i < BOARD_SIZE; i++){
System.out.println("");
for (int j = 0; j <BOARD_SIZE; j++){
System.out.print(board [i][j] + " ");
}
}
}
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;
}
}
private void setQueen(int row, int column) {
board [row][column] = QUEEN;
}
private void removeQueen(int row, int column) {
board [row][column] = EMPTY;
}
private boolean isUnderAttack(int row, int column) {
for (int j = 0; j < column; j++){
if (board[row][j] == QUEEN)
return true;
}
for (int j =column+1; j < BOARD_SIZE; j++){
if(board[row][j] == QUEEN)
return true;
}
for (int i = 1+row, j = 1+column; i < BOARD_SIZE && j < BOARD_SIZE; i++, j++){
if (board[i][j] == QUEEN)
return true;
}
for (int i= 1-row, j = 1-column; i >= 0 && j >=0; i--, j--){
if (board[i][j] == QUEEN)
return true;
}
for (int i= 1+row, j = 1-column; i < BOARD_SIZE && j >= 0; i++, j--){
if (board[i][j] == QUEEN)
return true;
}
for (int i= 1-row, j = 1+column; i >= 0 && j < BOARD_SIZE; i--, j++){
if (board[i][j] == QUEEN)
return true;
}
return false;
}
private int index(int number) {
return number -1;
}
}
source
share