java 8皇后 代码
时间: 2024-05-26 22:09:09 浏览: 16
Java 8皇后问题是经典的回溯算法问题。该问题是要求在一个8x8的棋盘上放置8个皇后,使得每个皇后都不会互相攻击。在这里,我们可以将每个皇后看作是在一行中放置,因此我们可以使用一个数组来表示每个皇后所在的列。
以下是一个简单的Java 8皇后问题的实现示例代码:
```
public class EightQueens {
private static final int BOARD_SIZE = 8;
public static void main(String[] args) {
int[] board = new int[BOARD_SIZE];
placeQueens(board, 0);
}
private static void placeQueens(int[] board, int row) {
if (row == BOARD_SIZE) {
printBoard(board);
} else {
for (int col = 0; col < BOARD_SIZE; col++) {
if (isValid(board, row, col)) {
board[row] = col;
placeQueens(board, row + 1);
}
}
}
}
private static boolean isValid(int[] board, int row, int col) {
for (int i = 0; i < row; i++) {
if (board[i] == col ||
board[i] - i == col - row ||
board[i] + i == col + row) {
return false;
}
}
return true;
}
private static void printBoard(int[] board) {
for (int row = 0; row < BOARD_SIZE; row++) {
for (int col = 0; col < BOARD_SIZE; col++) {
if (board[row] == col) {
System.out.print("Q ");
} else {
System.out.print("* ");
}
}
System.out.println();
}
System.out.println();
}
}
```
这个代码使用了递归和回溯算法来实现。它使用一个一维数组来表示每个皇后所在的列,每次递归时检查是否有冲突并找到下一个合适的位置来放置下一个皇后。