N皇后怎么写 用Java语言
时间: 2023-03-24 08:01:48 浏览: 53
如果您是指如何用 Java 语言书写“N 皇后”问题的解决方案,那么以下是一个基本的实现:
```
import java.util.*;
public class NQueens {
private int n;
private int[] cols;
private int[] diag1;
private int[] diag2;
private List<List<String>> solutions;
public List<List<String>> solveNQueens(int n) {
this.n = n;
this.cols = new int[n];
this.diag1 = new int[2*n - 1];
this.diag2 = new int[2*n - 1];
this.solutions = new ArrayList<>();
backtrack(0, new ArrayList<>());
return solutions;
}
private void backtrack(int row, List<String> board) {
if (row == n) {
solutions.add(new ArrayList<>(board));
return;
}
for (int col = 0; col < n; col++) {
if (isNotUnderAttack(row, col)) {
placeQueen(row, col);
board.add(getBoardRow(col));
backtrack(row + 1, board);
removeQueen(row, col);
board.remove(board.size() - 1);
}
}
}
private boolean isNotUnderAttack(int row, int col) {
int res = cols[col] + diag1[row - col + n - 1] + diag2[row + col];
return res == 0;
}
private void placeQueen(int row, int col) {
cols[col] = 1;
diag1[row - col + n - 1] = 1;
diag2[row + col] = 1;
}
private void removeQueen(int row, int col) {
cols[col] = 0;
diag1[row - col + n - 1] = 0;
diag2[row + col] = 0;
}
private String getBoardRow(int col) {
char[] row = new char[n];
Arrays.fill(row, '.');
row[col] = 'Q';
return new String(row);
}
}
```
此代码通过回溯法来求解 N 皇后问题,使用了三个数组来记录每一列、两条对角线上是否已经有皇后。代码中使用了一个 List<List<String>> 变量来存储所有解法,每个解法以一个 List<String> 变量来表示棋盘。其中,每个字符串表示棋盘的一行,其中“Q”表示皇后,"."表示空格。
您可以通过调用 `solveNQueens(n)` 方法来求解 N 皇后问题,其中 n 表示皇后数量。返回值为一个 List<List<String>> 变量,表示所有解法。