java使用回溯法求解n皇后问题
时间: 2023-11-29 20:44:46 浏览: 82
N_queen.zip_n queen问题_queen
以下是Java使用回溯法求解N皇后问题的代码示例:
```java
public class NQueens {
private int n;
private int[] queens;
private boolean[] colUsed;
private boolean[] diagonal1Used;
private boolean[] diagonal2Used;
private List<List<String>> res;
public List<List<String>> solveNQueens(int n) {
this.n = n;
queens = new int[n];
colUsed = new boolean[n];
diagonal1Used = new boolean[2 * n - 1];
diagonal2Used = new boolean[2 * n - 1];
res = new ArrayList<>();
dfs(0);
return res;
}
private void dfs(int row) {
if (row == n) {
res.add(generateBoard());
return;
}
for (int col = 0; col < n; col++) {
int diagonal1 = row + col;
int diagonal2 = n - 1 - row + col;
if (colUsed[col] || diagonal1Used[diagonal1] || diagonal2Used[diagonal2]) {
continue;
}
queens[row] = col;
colUsed[col] = true;
diagonal1Used[diagonal1] = true;
diagonal2Used[diagonal2] = true;
dfs(row + 1);
queens[row] = 0;
colUsed[col] = false;
diagonal1Used[diagonal1] = false;
diagonal2Used[diagonal2] = false;
}
}
private List<String> generateBoard() {
List<String> board = new ArrayList<>();
for (int i = 0; i < n; i++) {
char[] row = new char[n];
Arrays.fill(row, '.');
row[queens[i]] = 'Q';
board.add(new String(row)); }
return board;
}
}
```
阅读全文