八皇后二维数组java
时间: 2023-11-10 17:03:01 浏览: 41
以下是八皇后问题的二维数组Java代码:
```
public class EightQueens {
private static final int BOARD_SIZE = 8;
private static int[][] board = new int[BOARD_SIZE][BOARD_SIZE];
public static void main(String[] args) {
placeQueens(0);
printBoard();
}
private static boolean placeQueens(int row) {
if (row == BOARD_SIZE) {
return true;
}
for (int col = 0; col < BOARD_SIZE; col++) {
if (isSafe(row, col)) {
board[row][col] = 1;
if (placeQueens(row + 1)) {
return true;
}
board[row][col] = 0;
}
}
return false;
}
private static boolean isSafe(int row, int col) {
for (int i = 0; i < row; i++) {
if (board[i][col] == 1) {
return false;
}
}
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1) {
return false;
}
}
for (int i = row, j = col; i >= 0 && j < BOARD_SIZE; i--, j++) {
if (board[i][j] == 1) {
return false;
}
}
return true;
}
private static void printBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}
```