Java 八皇后问题解决方案 | 代码示例和解释
八皇后问题是一个经典的计算机科学问题,它旨在找到一种在 8x8 的棋盘上放置 8 个皇后的方式,使得没有两个皇后在同一行,同一列或同一对角线上。以下是 Java 解决八皇后问题的示例代码:
public class EightQueensProblem {
private static final int BOARD_SIZE = 8;
private static int[][] board = new int[BOARD_SIZE][BOARD_SIZE];
public static void main(String[] args) {
solveQueensProblem(0);
}
private static void solveQueensProblem(int colIndex) {
if (colIndex == BOARD_SIZE) {
printQueens();
return;
}
for (int rowIndex = 0; rowIndex < BOARD_SIZE; rowIndex++) {
if (isPlaceValid(rowIndex, colIndex)) {
board[rowIndex][colIndex] = 1;
solveQueensProblem(colIndex + 1);
board[rowIndex][colIndex] = 0;
}
}
}
private static boolean isPlaceValid(int rowIndex, int colIndex) {
for (int i = 0; i < colIndex; i++) {
if (board[rowIndex][i] == 1) {
return false;
}
}
for (int i = rowIndex, j = colIndex; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1) {
return false;
}
}
for (int i = rowIndex, j = colIndex; i < BOARD_SIZE && j >= 0; i++, j--) {
if (board[i][j] == 1) {
return false;
}
}
return true;
}
private static void printQueens() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == 1) {
System.out.print("Q ");
} else {
System.out.print("- ");
}
}
System.out.println();
}
System.out.println();
}
}
在这个示例代码中,我们使用一个二维数组来表示棋盘,其中 1 表示皇后,0 表示空格。我们使用递归方法来解决问题,每次尝试在当前列放置皇后,如果当前位置可行,则递归调用该方法来放置下一列的皇后。如果我们成功放置 8 个皇后,则打印出解决方案。在检查当前位置是否可行时,我们检查该行、该列和对角线上是否有其他皇后。如果没有其他皇后,则当前位置可行。最后,我们使用 printQueens 方法打印出结果。
原文地址: https://www.cveoy.top/t/topic/mVNc 著作权归作者所有。请勿转载和采集!