用java写一个八皇后问题
时间: 2023-12-30 09:03:45 浏览: 67
好的,下面是用 Java 实现八皇后问题的代码:
```java
public class EightQueens {
private static final int BOARD_SIZE = 8;
private static int[] queens = new int[BOARD_SIZE];
public static void main(String[] args) {
placeQueen(0);
}
private static void placeQueen(int row) {
if (row == BOARD_SIZE) {
printBoard();
return;
}
for (int col = 0; col < BOARD_SIZE; col++) {
if (isValidPosition(row, col)) {
queens[row] = col;
placeQueen(row + 1);
}
}
}
private static boolean isValidPosition(int row, int col) {
for (int i = 0; i < row; i++) {
if (queens[i] == col || queens[i] - i == col - row || queens[i] + i == col + row) {
return false;
}
}
return true;
}
private static void printBoard() {
for (int row = 0; row < BOARD_SIZE; row++) {
for (int col = 0; col < BOARD_SIZE; col++) {
if (queens[row] == col) {
System.out.print("Q ");
} else {
System.out.print(". ");
}
}
System.out.println();
}
System.out.println();
}
}
```
以上代码运行后会输出所有的八皇后解法。
阅读全文