mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-21 02:56:11 +00:00
build
This commit is contained in:
@@ -52,6 +52,97 @@ comments: true
|
||||
|
||||
请注意,$n$ 维方阵中 $row - col$ 的范围是 $[-n + 1, n - 1]$ ,$row + col$ 的范围是 $[0, 2n - 2]$ ,所以主对角线和次对角线的数量都为 $2n - 1$ ,即数组 `diag1` 和 `diag2` 的长度都为 $2n - 1$ 。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="n_queens.py"
|
||||
def backtrack(
|
||||
row: int,
|
||||
n: int,
|
||||
state: list[list[str]],
|
||||
res: list[list[list[str]]],
|
||||
cols: list[bool],
|
||||
diags1: list[bool],
|
||||
diags2: list[bool],
|
||||
):
|
||||
"""回溯算法:N 皇后"""
|
||||
# 当放置完所有行时,记录解
|
||||
if row == n:
|
||||
res.append([list(row) for row in state])
|
||||
return
|
||||
# 遍历所有列
|
||||
for col in range(n):
|
||||
# 计算该格子对应的主对角线和副对角线
|
||||
diag1 = row - col + n - 1
|
||||
diag2 = row + col
|
||||
# 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if not cols[col] and not diags1[diag1] and not diags2[diag2]:
|
||||
# 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = True
|
||||
# 放置下一行
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2)
|
||||
# 回退:将该格子恢复为空位
|
||||
state[row][col] = "#"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = False
|
||||
|
||||
def n_queens(n: int) -> list[list[list[str]]]:
|
||||
"""求解 N 皇后"""
|
||||
# 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
state = [["#" for _ in range(n)] for _ in range(n)]
|
||||
cols = [False] * n # 记录列是否有皇后
|
||||
diags1 = [False] * (2 * n - 1) # 记录主对角线是否有皇后
|
||||
diags2 = [False] * (2 * n - 1) # 记录副对角线是否有皇后
|
||||
res = []
|
||||
backtrack(0, n, state, res, cols, diags1, diags2)
|
||||
|
||||
return res
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="n_queens.cpp"
|
||||
/* 回溯算法:N 皇后 */
|
||||
void backtrack(int row, int n, vector<vector<string>> &state, vector<vector<vector<string>>> &res, vector<bool> &cols,
|
||||
vector<bool> &diags1, vector<bool> &diags2) {
|
||||
// 当放置完所有行时,记录解
|
||||
if (row == n) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// 遍历所有列
|
||||
for (int col = 0; col < n; col++) {
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
int diag1 = row - col + n - 1;
|
||||
int diag2 = row + col;
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// 放置下一行
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// 回退:将该格子恢复为空位
|
||||
state[row][col] = "#";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
vector<vector<vector<string>>> nQueens(int n) {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
vector<vector<string>> state(n, vector<string>(n, "#"));
|
||||
vector<bool> cols(n, false); // 记录列是否有皇后
|
||||
vector<bool> diags1(2 * n - 1, false); // 记录主对角线是否有皇后
|
||||
vector<bool> diags2(2 * n - 1, false); // 记录副对角线是否有皇后
|
||||
vector<vector<vector<string>>> res;
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="n_queens.java"
|
||||
@@ -108,15 +199,19 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
=== "C#"
|
||||
|
||||
```cpp title="n_queens.cpp"
|
||||
```csharp title="n_queens.cs"
|
||||
/* 回溯算法:N 皇后 */
|
||||
void backtrack(int row, int n, vector<vector<string>> &state, vector<vector<vector<string>>> &res, vector<bool> &cols,
|
||||
vector<bool> &diags1, vector<bool> &diags2) {
|
||||
void backtrack(int row, int n, List<List<string>> state, List<List<List<string>>> res,
|
||||
bool[] cols, bool[] diags1, bool[] diags2) {
|
||||
// 当放置完所有行时,记录解
|
||||
if (row == n) {
|
||||
res.push_back(state);
|
||||
List<List<string>> copyState = new List<List<string>>();
|
||||
foreach (List<string> sRow in state) {
|
||||
copyState.Add(new List<string>(sRow));
|
||||
}
|
||||
res.Add(copyState);
|
||||
return;
|
||||
}
|
||||
// 遍历所有列
|
||||
@@ -139,13 +234,20 @@ comments: true
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
vector<vector<vector<string>>> nQueens(int n) {
|
||||
List<List<List<string>>> nQueens(int n) {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
vector<vector<string>> state(n, vector<string>(n, "#"));
|
||||
vector<bool> cols(n, false); // 记录列是否有皇后
|
||||
vector<bool> diags1(2 * n - 1, false); // 记录主对角线是否有皇后
|
||||
vector<bool> diags2(2 * n - 1, false); // 记录副对角线是否有皇后
|
||||
vector<vector<vector<string>>> res;
|
||||
List<List<string>> state = new List<List<string>>();
|
||||
for (int i = 0; i < n; i++) {
|
||||
List<string> row = new List<string>();
|
||||
for (int j = 0; j < n; j++) {
|
||||
row.Add("#");
|
||||
}
|
||||
state.Add(row);
|
||||
}
|
||||
bool[] cols = new bool[n]; // 记录列是否有皇后
|
||||
bool[] diags1 = new bool[2 * n - 1]; // 记录主对角线是否有皇后
|
||||
bool[] diags2 = new bool[2 * n - 1]; // 记录副对角线是否有皇后
|
||||
List<List<List<string>>> res = new List<List<List<string>>>();
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
|
||||
@@ -153,52 +255,6 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="n_queens.py"
|
||||
def backtrack(
|
||||
row: int,
|
||||
n: int,
|
||||
state: list[list[str]],
|
||||
res: list[list[list[str]]],
|
||||
cols: list[bool],
|
||||
diags1: list[bool],
|
||||
diags2: list[bool],
|
||||
):
|
||||
"""回溯算法:N 皇后"""
|
||||
# 当放置完所有行时,记录解
|
||||
if row == n:
|
||||
res.append([list(row) for row in state])
|
||||
return
|
||||
# 遍历所有列
|
||||
for col in range(n):
|
||||
# 计算该格子对应的主对角线和副对角线
|
||||
diag1 = row - col + n - 1
|
||||
diag2 = row + col
|
||||
# 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if not cols[col] and not diags1[diag1] and not diags2[diag2]:
|
||||
# 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = True
|
||||
# 放置下一行
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2)
|
||||
# 回退:将该格子恢复为空位
|
||||
state[row][col] = "#"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = False
|
||||
|
||||
def n_queens(n: int) -> list[list[list[str]]]:
|
||||
"""求解 N 皇后"""
|
||||
# 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
state = [["#" for _ in range(n)] for _ in range(n)]
|
||||
cols = [False] * n # 记录列是否有皇后
|
||||
diags1 = [False] * (2 * n - 1) # 记录主对角线是否有皇后
|
||||
diags2 = [False] * (2 * n - 1) # 记录副对角线是否有皇后
|
||||
res = []
|
||||
backtrack(0, n, state, res, cols, diags1, diags2)
|
||||
|
||||
return res
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="n_queens.go"
|
||||
@@ -284,6 +340,54 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="n_queens.swift"
|
||||
/* 回溯算法:N 皇后 */
|
||||
func backtrack(row: Int, n: Int, state: inout [[String]], res: inout [[[String]]], cols: inout [Bool], diags1: inout [Bool], diags2: inout [Bool]) {
|
||||
// 当放置完所有行时,记录解
|
||||
if row == n {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// 遍历所有列
|
||||
for col in 0 ..< n {
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
let diag1 = row - col + n - 1
|
||||
let diag2 = row + col
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q"
|
||||
cols[col] = true
|
||||
diags1[diag1] = true
|
||||
diags2[diag2] = true
|
||||
// 放置下一行
|
||||
backtrack(row: row + 1, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
// 回退:将该格子恢复为空位
|
||||
state[row][col] = "#"
|
||||
cols[col] = false
|
||||
diags1[diag1] = false
|
||||
diags2[diag2] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
func nQueens(n: Int) -> [[[String]]] {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
var state = Array(repeating: Array(repeating: "#", count: n), count: n)
|
||||
var cols = Array(repeating: false, count: n) // 记录列是否有皇后
|
||||
var diags1 = Array(repeating: false, count: 2 * n - 1) // 记录主对角线是否有皇后
|
||||
var diags2 = Array(repeating: false, count: 2 * n - 1) // 记录副对角线是否有皇后
|
||||
var res: [[[String]]] = []
|
||||
|
||||
backtrack(row: 0, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="n_queens.js"
|
||||
@@ -378,126 +482,6 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="n_queens.c"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{nQueens}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="n_queens.cs"
|
||||
/* 回溯算法:N 皇后 */
|
||||
void backtrack(int row, int n, List<List<string>> state, List<List<List<string>>> res,
|
||||
bool[] cols, bool[] diags1, bool[] diags2) {
|
||||
// 当放置完所有行时,记录解
|
||||
if (row == n) {
|
||||
List<List<string>> copyState = new List<List<string>>();
|
||||
foreach (List<string> sRow in state) {
|
||||
copyState.Add(new List<string>(sRow));
|
||||
}
|
||||
res.Add(copyState);
|
||||
return;
|
||||
}
|
||||
// 遍历所有列
|
||||
for (int col = 0; col < n; col++) {
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
int diag1 = row - col + n - 1;
|
||||
int diag2 = row + col;
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// 放置下一行
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// 回退:将该格子恢复为空位
|
||||
state[row][col] = "#";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
List<List<List<string>>> nQueens(int n) {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
List<List<string>> state = new List<List<string>>();
|
||||
for (int i = 0; i < n; i++) {
|
||||
List<string> row = new List<string>();
|
||||
for (int j = 0; j < n; j++) {
|
||||
row.Add("#");
|
||||
}
|
||||
state.Add(row);
|
||||
}
|
||||
bool[] cols = new bool[n]; // 记录列是否有皇后
|
||||
bool[] diags1 = new bool[2 * n - 1]; // 记录主对角线是否有皇后
|
||||
bool[] diags2 = new bool[2 * n - 1]; // 记录副对角线是否有皇后
|
||||
List<List<List<string>>> res = new List<List<List<string>>>();
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="n_queens.swift"
|
||||
/* 回溯算法:N 皇后 */
|
||||
func backtrack(row: Int, n: Int, state: inout [[String]], res: inout [[[String]]], cols: inout [Bool], diags1: inout [Bool], diags2: inout [Bool]) {
|
||||
// 当放置完所有行时,记录解
|
||||
if row == n {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// 遍历所有列
|
||||
for col in 0 ..< n {
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
let diag1 = row - col + n - 1
|
||||
let diag2 = row + col
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q"
|
||||
cols[col] = true
|
||||
diags1[diag1] = true
|
||||
diags2[diag2] = true
|
||||
// 放置下一行
|
||||
backtrack(row: row + 1, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
// 回退:将该格子恢复为空位
|
||||
state[row][col] = "#"
|
||||
cols[col] = false
|
||||
diags1[diag1] = false
|
||||
diags2[diag2] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
func nQueens(n: Int) -> [[[String]]] {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
var state = Array(repeating: Array(repeating: "#", count: n), count: n)
|
||||
var cols = Array(repeating: false, count: n) // 记录列是否有皇后
|
||||
var diags1 = Array(repeating: false, count: 2 * n - 1) // 记录主对角线是否有皇后
|
||||
var diags2 = Array(repeating: false, count: 2 * n - 1) // 记录副对角线是否有皇后
|
||||
var res: [[[String]]] = []
|
||||
|
||||
backtrack(row: 0, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="n_queens.zig"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{nQueens}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="n_queens.dart"
|
||||
@@ -614,6 +598,22 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="n_queens.c"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{nQueens}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="n_queens.zig"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{nQueens}
|
||||
```
|
||||
|
||||
逐行放置 $n$ 次,考虑列约束,则从第一行到最后一行分别有 $n$、$n-1$、$\dots$、$2$、$1$ 个选择,**因此时间复杂度为 $O(n!)$** 。实际上,根据对角线约束的剪枝也能够大幅地缩小搜索空间,因而搜索效率往往优于以上时间复杂度。
|
||||
|
||||
数组 `state` 使用 $O(n^2)$ 空间,数组 `cols`、`diags1` 和 `diags2` 皆使用 $O(n)$ 空间。最大递归深度为 $n$ ,使用 $O(n)$ 栈帧空间。因此,**空间复杂度为 $O(n^2)$** 。
|
||||
|
||||
Reference in New Issue
Block a user