我正在做 8 个皇后问题的一个版本,但没有使用回溯方法。对于其中一种方法,我必须“对正方形进行评分”,基本上我需要找出如果要在盒子中放置女王,则将变得不可用的单元格数量。我的问题是我无法让我的代码返回正方形的分数。我的 for 循环有什么问题吗?
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;
}
}