Update n queens.

This commit is contained in:
krahets 2023-05-05 03:42:01 +08:00
parent 7b1de228a0
commit db6caf0d43
2 changed files with 22 additions and 22 deletions

View file

@ -9,27 +9,6 @@ package chapter_backtracking;
import java.util.*;
public class n_queens {
/* 求解 N 皇后 */
public static List<List<List<String>>> nQueens(int n) {
// 初始化 n*n 大小的棋盘其中 'Q' 代表皇后'#' 代表空位
List<List<String>> state = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<String> row = new ArrayList<>();
for (int j = 0; j < n; j++) {
row.add("#");
}
state.add(row);
}
boolean[] cols = new boolean[n]; // 记录列是否有皇后
boolean[] diags1 = new boolean[2 * n - 1]; // 记录主对角线是否有皇后
boolean[] diags2 = new boolean[2 * n - 1]; // 记录副对角线是否有皇后
List<List<List<String>>> res = new ArrayList<>();
backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
/* 回溯算法N 皇后 */
public static void backtrack(int row, int n, List<List<String>> state, List<List<List<String>>> res,
boolean[] cols, boolean[] diags1, boolean[] diags2) {
@ -61,6 +40,27 @@ public class n_queens {
}
}
/* 求解 N 皇后 */
public static List<List<List<String>>> nQueens(int n) {
// 初始化 n*n 大小的棋盘其中 'Q' 代表皇后'#' 代表空位
List<List<String>> state = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<String> row = new ArrayList<>();
for (int j = 0; j < n; j++) {
row.add("#");
}
state.add(row);
}
boolean[] cols = new boolean[n]; // 记录列是否有皇后
boolean[] diags1 = new boolean[2 * n - 1]; // 记录主对角线是否有皇后
boolean[] diags2 = new boolean[2 * n - 1]; // 记录副对角线是否有皇后
List<List<List<String>>> res = new ArrayList<>();
backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
public static void main(String[] args) {
int n = 4;
List<List<List<String>>> res = nQueens(n);

View file

@ -190,7 +190,7 @@ nav:
- 13. &nbsp; &nbsp; 回溯算法:
- 13.1. &nbsp; 回溯算法New: chapter_backtracking/backtracking_algorithm.md
- 13.2. &nbsp; 全排列问题New: chapter_backtracking/permutations_problem.md
- 13.3. &nbsp; n 皇后问题New: chapter_backtracking/n_queens_problem.md
- 13.3. &nbsp; N 皇后问题New: chapter_backtracking/n_queens_problem.md
- 14. &nbsp; &nbsp; 附录:
- 14.1. &nbsp; 编程环境安装: chapter_appendix/installation.md
- 14.2. &nbsp; 一起参与创作: chapter_appendix/contribution.md