帮我写个java的n皇后算法
时间: 2023-05-29 07:07:45 浏览: 52
下面是一个Java的n皇后算法:
```
public class NQueens {
private int[] queens;
private int n;
public NQueens(int n) {
this.n = n;
queens = new int[n];
}
public void solve() {
placeQueen(0);
}
private boolean canPlaceQueen(int row, int col) {
for (int i = 0; i < row; i++) {
int otherCol = queens[i];
if (col == otherCol) {
return false;
}
int colDiff = Math.abs(col - otherCol);
int rowDiff = row - i;
if (colDiff == rowDiff) {
return false;
}
}
return true;
}
private void placeQueen(int row) {
if (row == n) {
printQueens();
return;
}
for (int col = 0; col < n; col++) {
if (canPlaceQueen(row, col)) {
queens[row] = col;
placeQueen(row + 1);
}
}
}
private void printQueens() {
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
if (queens[row] == col) {
System.out.print("Q ");
} else {
System.out.print(". ");
}
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
NQueens nQueens = new NQueens(8);
nQueens.solve();
}
}
```
在这个算法中,我们使用一个一维数组来表示皇后的位置,数组的下标表示行,数组中的值表示列。我们从第0行开始,依次在每一行放置皇后,如果发现当前位置可以放置皇后,我们就递归地继续放置下一行的皇后。当放置到最后一行时,我们就找到了一组解,并打印出来。对于每个位置,我们需要检查它是否与已经放置的皇后位置冲突,如果冲突就不能放置。我们使用了一个canPlaceQueen方法来进行检查。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)