java解决八皇后问题
八皇后问题是指在8×8的国际象棋棋盘上放置8个皇后,使得任意两个皇后都不能在同一行、同一列或同一斜线上。这是一个经典的回溯算法问题,可以使用Java语言进行解决。
以下是Java解决八皇后问题的代码:
public class EightQueens {
private static final int BOARD_SIZE = 8; // 棋盘大小
private static int[] queens = new int[BOARD_SIZE]; // 皇后位置数组
// 判断皇后是否能够放置
private static boolean isSafe(int row, int col) {
for (int i = 0; i < row; i++) {
int diff = Math.abs(queens[i] - col);
if (diff == 0 || diff == row - i) {
return false;
}
}
return true;
}
// 回溯算法求解八皇后问题
private static boolean solve(int row) {
if (row == BOARD_SIZE) {
return true;
}
for (int col = 0; col < BOARD_SIZE; col++) {
if (isSafe(row, col)) {
queens[row] = col;
if (solve(row + 1)) {
return true;
}
}
}
return false;
}
// 打印出皇后的位置
private static void printQueens() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (queens[i] == j) {
System.out.print("Q ");
} else {
System.out.print(". ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
if (solve(0)) {
printQueens();
} else {
System.out.println("无解");
}
}
}
这段代码中,isSafe方法用于判断皇后是否能够放置,solve方法用于回溯求解八皇后问题,printQueens方法用于打印出皇后的位置。
在main方法中,首先调用solve方法求解八皇后问题,如果有解则调用printQueens方法打印出皇后的位置,否则输出无解。
原文地址: https://www.cveoy.top/t/topic/bsrd 著作权归作者所有。请勿转载和采集!