diff --git a/codes/java/chapter_backtracking/n_queens.java b/codes/java/chapter_backtracking/n_queens.java index b9a7e7702..6705ebc16 100644 --- a/codes/java/chapter_backtracking/n_queens.java +++ b/codes/java/chapter_backtracking/n_queens.java @@ -9,27 +9,6 @@ package chapter_backtracking; import java.util.*; public class n_queens { - /* 求解 N 皇后 */ - public static List>> nQueens(int n) { - // 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位 - List> state = new ArrayList<>(); - for (int i = 0; i < n; i++) { - List 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>> res = new ArrayList<>(); - - backtrack(0, n, state, res, cols, diags1, diags2); - - return res; - } - /* 回溯算法:N 皇后 */ public static void backtrack(int row, int n, List> state, List>> res, boolean[] cols, boolean[] diags1, boolean[] diags2) { @@ -61,6 +40,27 @@ public class n_queens { } } + /* 求解 N 皇后 */ + public static List>> nQueens(int n) { + // 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位 + List> state = new ArrayList<>(); + for (int i = 0; i < n; i++) { + List 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>> res = new ArrayList<>(); + + backtrack(0, n, state, res, cols, diags1, diags2); + + return res; + } + public static void main(String[] args) { int n = 4; List>> res = nQueens(n); diff --git a/mkdocs.yml b/mkdocs.yml index 785b0102b..56017ca4e 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -190,7 +190,7 @@ nav: - 13.     回溯算法: - 13.1.   回溯算法(New): chapter_backtracking/backtracking_algorithm.md - 13.2.   全排列问题(New): chapter_backtracking/permutations_problem.md - - 13.3.   n 皇后问题(New): chapter_backtracking/n_queens_problem.md + - 13.3.   N 皇后问题(New): chapter_backtracking/n_queens_problem.md - 14.     附录: - 14.1.   编程环境安装: chapter_appendix/installation.md - 14.2.   一起参与创作: chapter_appendix/contribution.md