n皇后问题java递归
时间: 2023-11-12 21:57:43 浏览: 79
n皇后问题问题递归算法
好的,关于n皇后问题的Java递归实现,可以参考以下代码:
```
public class NQueens {
private int[] queens;
private int n;
public void solve(int n) {
this.n = n;
queens = new int[n];
placeQueen(0);
}
private void placeQueen(int row) {
if (row == n) {
printQueens();
return;
}
for (int col = 0; col < n; col++) {
if (isValid(row, col)) {
queens[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(queens[i] - col) == row - i) {
return false;
}
}
return true;
}
private void printQueens() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (queens[i] == j) {
System.out.print("Q ");
} else {
System.out.print(". ");
}
}
System.out.println();
}
System.out.println();
}
}
```
阅读全文