This commit is contained in:
krahets
2023-10-08 01:43:28 +08:00
parent 3d2d669b43
commit baac2d11a7
52 changed files with 999 additions and 625 deletions
+8 -8
View File
@@ -203,11 +203,11 @@ comments: true
```csharp title="n_queens.cs"
/* 回溯算法:N 皇后 */
void backtrack(int row, int n, List<List<string>> state, List<List<List<string>>> res,
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>>();
List<List<string>> copyState = new();
foreach (List<string> sRow in state) {
copyState.Add(new List<string>(sRow));
}
@@ -225,7 +225,7 @@ comments: true
state[row][col] = "Q";
cols[col] = diags1[diag1] = diags2[diag2] = true;
// 放置下一行
backtrack(row + 1, n, state, res, cols, diags1, diags2);
Backtrack(row + 1, n, state, res, cols, diags1, diags2);
// 回退:将该格子恢复为空位
state[row][col] = "#";
cols[col] = diags1[diag1] = diags2[diag2] = false;
@@ -234,11 +234,11 @@ comments: true
}
/* 求解 N 皇后 */
List<List<List<string>>> nQueens(int n) {
List<List<List<string>>> NQueens(int n) {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
List<List<string>> state = new List<List<string>>();
List<List<string>> state = new();
for (int i = 0; i < n; i++) {
List<string> row = new List<string>();
List<string> row = new();
for (int j = 0; j < n; j++) {
row.Add("#");
}
@@ -247,9 +247,9 @@ comments: true
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>>>();
List<List<List<string>>> res = new();
backtrack(0, n, state, res, cols, diags1, diags2);
Backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}