八皇后问题是一个经典的回溯算法问题。以下是一个 Java 实现:

public class EightQueens {
    private static final int BOARD_SIZE = 8;
    private int[][] board;

    public EightQueens() {
        board = new int[BOARD_SIZE][BOARD_SIZE];
    }

    public void solve() {
        if (placeQueens(0)) {
            printBoard();
        } else {
            System.out.println('No solution found.');
        }
    }

    private boolean placeQueens(int row) {
        if (row == BOARD_SIZE) {
            return true;
        }

        for (int col = 0; col < BOARD_SIZE; col++) {
            if (isSafe(row, col)) {
                board[row][col] = 1;

                if (placeQueens(row + 1)) {
                    return true;
                }

                board[row][col] = 0;
            }
        }

        return false;
    }

    private boolean isSafe(int row, int col) {
        for (int i = 0; i < row; i++) {
            if (board[i][col] == 1) {
                return false;
            }
        }

        for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 1) {
                return false;
            }
        }

        for (int i = row, j = col; i >= 0 && j < BOARD_SIZE; i--, j++) {
            if (board[i][j] == 1) {
                return false;
            }
        }

        return true;
    }

    private void printBoard() {
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                System.out.print(board[i][j] + ' ');
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        EightQueens eq = new EightQueens();
        eq.solve();
    }
}

该程序创建一个 8x8 的棋盘,并使用回溯算法来放置 8 个皇后。isSafe() 方法检查当前皇后是否与之前的皇后冲突,如果没有,则将皇后放在当前位置。如果所有皇后都已放置在棋盘上,则打印棋盘。如果无法放置皇后,则返回 false。如果没有找到解决方案,则打印'No solution found.'。

Java 八皇后问题:回溯算法实现及解析

原文地址: https://www.cveoy.top/t/topic/mVM4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录