mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-05 03:36:39 +08:00
Java version of Nqueens
This commit is contained in:
@ -309,4 +309,67 @@ def backtrack(...):
|
|||||||
<img src="../pictures/qrcode.jpg" width=200 >
|
<img src="../pictures/qrcode.jpg" width=200 >
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
======其他语言代码======
|
======其他语言代码======
|
||||||
|
|
||||||
|
由[kepler-zc](https://github.com/kepler-zc) 提供 51.N皇后 Java 解法代码:
|
||||||
|
```java
|
||||||
|
class solution {
|
||||||
|
private List<List<String>> res = new ArrayList<>();
|
||||||
|
|
||||||
|
// 输入棋盘边长 n,返回所有合法的放置
|
||||||
|
public List<List<String>> solveNQueens(int n){
|
||||||
|
// '.'表示空,'Q'表示皇后,初始化空棋盘
|
||||||
|
char[][] chess = new char[n][n];
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
Arrays.fill(chess[i], '.');
|
||||||
|
}
|
||||||
|
// 已经不能放置皇后的列(被占用)
|
||||||
|
boolean[] usedCol = new boolean[n];
|
||||||
|
// 已经不能放置皇后的正斜线 , 按右上角到左下角排列 , 共2n-1条
|
||||||
|
boolean[] usedSlash = new boolean[2*n-1];
|
||||||
|
// 已经不能放置皇后的反斜线 , 按左上角到右下角排列 , 共2n-1条
|
||||||
|
boolean[] usedBackSlash = new boolean[2*n-1];
|
||||||
|
backtrack(chess, 0, usedCol, usedSlash, usedBackSlash);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 路径:chess 中小于 row 的那些行都已经成功放置了皇后
|
||||||
|
// 选择列表:第 row 行的所有列都是放置皇后的选择
|
||||||
|
// 结束条件:row 超过 棋盘最后一行
|
||||||
|
private void backtrack(char[][] chess, int row, boolean[] usedCol, boolean[] usedSlash, boolean[] usedBackSlash) {
|
||||||
|
// 触发结束条件
|
||||||
|
if (row == chess.length){
|
||||||
|
res.add(construct(chess));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (int col = 0; col < chess.length; col++) {
|
||||||
|
// 对合法选择进行回溯操作
|
||||||
|
// 分别检查列,左上方, 右上方是否存在皇后冲突,都不冲突集为合法选择。
|
||||||
|
if (!usedCol[col] && !usedSlash[row-col+usedCol.length-1] && !usedBackSlash[col+row]){
|
||||||
|
// 做选择
|
||||||
|
chess[row][col] = 'Q';
|
||||||
|
usedCol[col] = true;
|
||||||
|
// 对坐标为[i,j]的点对应的正斜线和反斜线的索引分别为:row-col+n-1; col+row
|
||||||
|
usedSlash[row-col+chess.length-1] = true;
|
||||||
|
usedBackSlash[col+row] = true;
|
||||||
|
// 进入下一行
|
||||||
|
backtrack(chess, row+1, usedCol,usedSlash, usedBackSlash);
|
||||||
|
// 撤销选择
|
||||||
|
chess[row][col] = '.';
|
||||||
|
usedCol[col] = false;
|
||||||
|
usedSlash[row-col+chess.length-1] = false;
|
||||||
|
usedBackSlash[col+row] = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> construct(char[][] chess) {
|
||||||
|
// 数组转List
|
||||||
|
List<String> path = new ArrayList<>();
|
||||||
|
for (char[] chars : chess) {
|
||||||
|
path.add(new String(chars));
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
Reference in New Issue
Block a user