Java 八皇后问题解决方案 - 回溯算法实现
八皇后问题是指在 8×8 的国际象棋棋盘上放置 8 个皇后,使得任意两个皇后都不能在同一行、同一列或同一斜线上。可以使用回溯算法来解决八皇后问题。
以下是 Java 代码实现:
public class EightQueens {
private static final int BOARD_SIZE = 8;
private int[] queens = new int[BOARD_SIZE];
public void solve() {
placeQueen(0);
}
private void placeQueen(int row) {
if (row == BOARD_SIZE) {
printQueens();
return;
}
for (int col = 0; col < BOARD_SIZE; col++) {
queens[row] = col;
if (isValid(row, col)) {
placeQueen(row + 1);
}
}
}
private boolean isValid(int row, int col) {
for (int i = 0; i < row; i++) {
if (queens[i] == col || Math.abs(row - i) == Math.abs(col - queens[i])) {
return false;
}
}
return true;
}
private 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();
}
System.out.println();
}
public static void main(String[] args) {
EightQueens solver = new EightQueens();
solver.solve();
}
}
在上述代码中,queens数组表示每一行皇后所在的列号。placeQueen方法递归地尝试在每一行放置皇后,如果找到了一组解就输出。isValid方法用于判断当前位置是否合法,即是否与已有的皇后在同一列、同一行或同一斜线上。printQueens方法用于输出一组解。在main方法中调用solve方法即可求解八皇后问题。
原文地址: https://www.cveoy.top/t/topic/mVM1 著作权归作者所有。请勿转载和采集!