1

我正在做 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;
    }

}
4

1 回答 1

0

在您比较rc为零的每个循环中,您需要使用>=而不是<. 例如,在这个循环中,您需要使用c >= 0而不是c < 0

for (int r = row + 1, c = col - 1; r < board.length && c < 0; r++, c--) {

这是因为您正在倒数零,因此您希望在计数器高于零时继续计数。

最后,虽然它不应该影响您的结果,但您实际上并不需要前两个循环,因为它们中的每一个都应该只导致添加nboard.length即任何行或列的大小)。

于 2013-12-10T06:24:21.607 回答