I am doing a version of the 8 queens problem, but not using the backtracking method. For one of the methods, I have to "score the square", basically I need to find the number of cells that would become unavailable were there to be a queen placed in the box. My problem is that I cannot get my code to return the score of the square. Is there something wrong with my for loops or something?
import java.util.ArrayList;
public class Chessboard {
private int[][] board;
public static final int QUEEN = -2;
public static final int SQUIGGLE = -1;
/**
* constructor initializes board to be of size n-by-n and containing all
* zeros
*/
public Chessboard(int n) {
board = new int[n][n];
}
/**
* returns the board
*/
public int[][] getBoard() {
return board;
}
/**
* returns SQUIGGLE if square at row, col contains SQUIGGLE returns QUEEN if
* square at row, col contains QUEEN otherwise, counts the number of squares
* that would become unavailable if the square at row, col were to receive a
* queen; this count is returned
*/
public int scoreSquare(int row, int col) {
if (board[row][col] == -1) {
return SQUIGGLE;
} else if (board[row][col] == -2) {
return QUEEN;
}
else {
int countsquare = 1;
for (int r = 0; r < board[col].length; r++) {
countsquare++;
}
for (int c = 0; c < board[row].length; c++) {
countsquare++;
}
for (int r = row + 1, c = col + 1; r < board.length
&& c < board.length; r++, c++) {
countsquare++;
}
for (int r = row + 1, c = col - 1; r < board.length && c < 0; r++, c--) {
countsquare++;
}
for (int r = row - 1, c = col + 1; r < 0 && c < board.length; r--, c++) {
countsquare++;
}
for (int r = row - 1, c = col - 1; r < 0 && c < 0; r--, c--) {
countsquare++;
}
return countsquare;
}
}
In every loop where you compare
r
orc
to zero, you need to use>=
instead of<
. For example, in this loop, you need to usec >= 0
as opposed toc < 0
:This is because you are counting down to zero and so you want to keep counting while your counter is above zero.
Finally, although it shouldn't affect your results, you don't really need your first two loops as each of them should just result in adding
n
(which isboard.length
, i.e., the size of any row or column).