13.4 n 皇后问题¶
Question
根据国际象棋的规则,皇后可以攻击与同处一行、一列或一条斜线上的棋子。给定 \(n\) 个皇后和一个 \(n \times n\) 大小的棋盘,寻找使得所有皇后之间无法相互攻击的摆放方案。
如图 13-15 所示,当 \(n = 4\) 时,共可以找到两个解。从回溯算法的角度看,\(n \times n\) 大小的棋盘共有 \(n^2\) 个格子,给出了所有的选择 choices 。在逐个放置皇后的过程中,棋盘状态在不断地变化,每个时刻的棋盘就是状态 state 。
图 13-15 4 皇后问题的解
图解 13-15:四皇后的两个解
左右棋盘分别给出 4 皇后问题的两个合法解。
4 皇后问题要求在 4×4 国际象棋棋盘上放置 4 枚皇后,使任意两枚皇后都不处于同一行、同一列或同一条对角线上。原图棋盘未标数字坐标;为便于定位,以下按行从上到下、列从左到右均从 1 开始编号。
下表按从上到下的行号查询左右棋盘的皇后所在列;其他方格为空。
| 行 | 左棋盘列 | 右棋盘列 |
|---|---|---|
| 1 | 2 | 3 |
| 2 | 4 | 1 |
| 3 | 1 | 4 |
| 4 | 3 | 2 |
两组摆放均为每行一枚、每列一枚;任意两枚皇后的行号之差绝对值不等于列号之差绝对值,因此也不在同一条主对角线或次对角线上。两者互为左右镜像,构成 4 皇后问题的全部解。
图 13-16 展示了本题的三个约束条件:多个皇后不能在同一行、同一列、同一条对角线上。值得注意的是,对角线分为主对角线 \ 和次对角线 / 两种。
图 13-16 n 皇后问题的约束条件
图解 13-16:皇后不能同行、同列或同对角线
左图展示单枚皇后在行、列与两条对角线上禁用的 11 个格,右图展示满足全部约束的 4 皇后合法解。
国际象棋中的皇后可沿水平行、竖直列以及主、次两条斜对角线攻击任意距离上的棋子。本图 4×4 棋盘按行从上到下、列从左到右均从 1 开始编号(1 基坐标)。
左棋盘在第 2 行第 2 列((2, 2))放一枚皇后,与它同行、同列或位于两条对角线上的其他格子都不能再放皇后,四个方向共排除 11 格。
右棋盘展示一组合法摆放。下方两表分别列出左棋盘皇后的禁用格与右棋盘各行所选列号。
| 方向 | 受攻击格 | 格数 |
|---|---|---|
| 同行 | (2,1)、(2,3)、(2,4) | 3 |
| 同列 | (1,2)、(3,2)、(4,2) | 3 |
| 主对角线(左上至右下) | (1,1)、(3,3)、(4,4) | 3 |
| 次对角线(右上至左下) | (1,3)、(3,1) | 2 |
| 行 | 皇后所在列 |
|---|---|
| 1 | 2 |
| 2 | 4 |
| 3 | 1 |
| 4 | 3 |
合法摆放必须同时满足不同行、不同列、不同主对角线和不同次对角线四项限制;按行逐枚放置虽能自然规避同行冲突,但仍需检查列与两条对角线。
1. 逐行放置策略¶
皇后的数量和棋盘的行数都为 \(n\) ,因此我们容易得到一个推论:棋盘每行都允许且只允许放置一个皇后。
也就是说,我们可以采取逐行放置策略:从第一行开始,在每行放置一个皇后,直至最后一行结束。
图 13-17 所示为 4 皇后问题的逐行放置过程。受画幅限制,图 13-17 仅展开了第一行的其中一个搜索分支,并且将不满足列约束和对角线约束的方案都进行了剪枝。
图 13-17 逐行放置策略
图解 13-17:逐行尝试与剪去冲突棋盘
以第一行放第 2 列的分支为例,展示四层 16 个候选棋盘的逐行试探与剪枝,确定各行所选列号组成的合法解 [2, 4, 1, 3]。
因每行恰好只能放置一枚皇后,回溯算法从第 1 行到第 4 行逐行放置以直接避免同行冲突;每层依次尝试该行第 1 至第 4 列,剪去与已放皇后同列或同对角线的分支。本图行列均从 1 开始编号。
图中只继续展开第一行第 2 列分支,之后三行依次保留第 4、1、3 列。第一行第 1、3、4 列的后续标为省略,表示图中没有展开,并非剪枝结论;其中第一行第 3 列对应另一个合法解 [3, 1, 4, 2]。
下表逐格列出图中的候选与处置。如果一格同时与多枚皇后冲突,图与表只标出其中一处,足以判定剪枝,并非列出全部冲突。例如 (4,2) 图示与 (3,1) 的主对角线冲突;按已放位置核算,它还与 (1,2) 同列、与 (2,4) 同次对角线。表中的“合法”只指当前一步不冲突,不保证该分支最终能完成一个解。
| 当前候选格 | 已放皇后 | 图中指出的冲突对象 | 冲突类型 | 处置 |
|---|---|---|---|---|
| (1,1) | 无 | 无 | 无冲突 | 合法,后续省略 |
| (1,2) | 无 | 无 | 无冲突 | 保留并继续 |
| (1,3) | 无 | 无 | 无冲突 | 合法,后续省略 |
| (1,4) | 无 | 无 | 无冲突 | 合法,后续省略 |
| (2,1) | (1,2) | (1,2) | 次对角线 | 剪去 |
| (2,2) | (1,2) | (1,2) | 同列 | 剪去 |
| (2,3) | (1,2) | (1,2) | 主对角线 | 剪去 |
| (2,4) | (1,2) | 无 | 无冲突 | 保留并继续 |
| (3,1) | (1,2)、(2,4) | 无 | 无冲突 | 保留并继续 |
| (3,2) | (1,2)、(2,4) | (1,2) | 同列 | 剪去 |
| (3,3) | (1,2)、(2,4) | (2,4) | 次对角线 | 剪去 |
| (3,4) | (1,2)、(2,4) | (2,4) | 同列 | 剪去 |
| (4,1) | (1,2)、(2,4)、(3,1) | (3,1) | 同列 | 剪去 |
| (4,2) | (1,2)、(2,4)、(3,1) | (3,1) | 主对角线 | 剪去 |
| (4,3) | (1,2)、(2,4)、(3,1) | 无 | 无冲突 | 保留并继续 |
| (4,4) | (1,2)、(2,4)、(3,1) | (2,4) | 同列 | 剪去 |
灰化并带剪枝标记的候选已违反约束;首行标为省略的合法分支则只是没有继续画出,两者含义不同。
从本质上看,逐行放置策略起到了剪枝的作用,它避免了同一行出现多个皇后的所有搜索分支。
2. 列与对角线剪枝¶
为了满足列约束,我们可以利用一个长度为 \(n\) 的布尔型数组 cols 记录每一列是否有皇后。在每次决定放置前,我们通过 cols 将已有皇后的列进行剪枝,并在回溯中动态更新 cols 的状态。
Tip
请注意,矩阵的起点位于左上角,其中行索引从上到下增加,列索引从左到右增加。
那么,如何处理对角线约束呢?设棋盘中某个格子的行列索引为 \((row, col)\) ,选定矩阵中的某条主对角线,我们发现该对角线上所有格子的行索引减列索引都相等,即主对角线上所有格子的 \(row - col\) 为恒定值。
也就是说,如果两个格子满足 \(row_1 - col_1 = row_2 - col_2\) ,则它们一定处在同一条主对角线上。利用该规律,我们可以借助图 13-18 所示的数组 diags1 记录每条主对角线上是否有皇后。
同理,次对角线上的所有格子的 \(row + col\) 是恒定值。我们同样也可以借助数组 diags2 来处理次对角线约束。
图 13-18 处理列约束和对角线约束
图解 13-18:用三个布尔数组记录皇后约束
用列数组 cols 与对角线数组 diags1、diags2,按零基行列坐标映射记录并检查皇后的占用状态。
本图对应代码实现:4×4 棋盘(n = 4)中行索引 row 从上到下、列索引 col 从左到右均从 0 开始(零基索引)。图中皇后位于零基坐标 (1, 1)(第 2 行第 2 列);布尔数组中 T 表示已占用,F 表示空闲。
同一主对角线的 row − col 相同,同一次对角线的 row + col 相同。候选格 (row, col) 分别用 col、row − col + n − 1、row + col 查找三个数组;三项都为 F 才能放入皇后。n = 4 时,row − col 的范围为 −3 至 3,加 3 后成为 0 至 6 的非负索引。
放入皇后时将对应三项置为 T,回溯时恢复为 F。下方两表分别列出索引规则与图中三个数组的完整值。
| 数组 | 长度 | 候选格对应索引 | 本例为 T 的索引 |
|---|---|---|---|
| cols | n = 4 | col | 1 |
| diags1 | 2n−1 = 7 | row−col+n−1 | 3 |
| diags2 | 2n−1 = 7 | row+col | 2 |
| 数组索引 | cols | diags1 | diags2 |
|---|---|---|---|
| 0 | F | F | F |
| 1 | T | F | F |
| 2 | F | F | T |
| 3 | F | T | F |
| 4 | 无此索引 | F | F |
| 5 | 无此索引 | F | F |
| 6 | 无此索引 | F | F |
借助 cols、diags1、diags2 三个布尔数组即可在常数时间内判断列与两条对角线是否冲突;一般的 n×n 棋盘共有 n 列,主对角线和次对角线各有 2n − 1 条。
3. 代码实现¶
请注意,\(n\) 维方阵中 \(row - col\) 的范围是 \([-n + 1, n - 1]\) ,\(row + col\) 的范围是 \([0, 2n - 2]\) ,所以主对角线和次对角线的数量都为 \(2n - 1\) ,即数组 diags1 和 diags2 的长度都为 \(2n - 1\) 。
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
/* 回溯算法: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;
}
/* 回溯算法:n 皇后 */
void backtrack(int row, int n, List<List<String>> state, List<List<List<String>>> res,
boolean[] cols, boolean[] diags1, boolean[] diags2) {
// 当放置完所有行时,记录解
if (row == n) {
List<List<String>> copyState = new ArrayList<>();
for (List<String> sRow : state) {
copyState.add(new ArrayList<>(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.get(row).set(col, "Q");
cols[col] = diags1[diag1] = diags2[diag2] = true;
// 放置下一行
backtrack(row + 1, n, state, res, cols, diags1, diags2);
// 回退:将该格子恢复为空位
state.get(row).set(col, "#");
cols[col] = diags1[diag1] = diags2[diag2] = false;
}
}
}
/* 求解 n 皇后 */
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 皇后 */
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 = [];
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 = [];
for (int i = 0; i < n; i++) {
List<string> row = [];
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 = [];
Backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
/* 回溯算法:n 皇后 */
func backtrack(row, n int, state *[][]string, res *[][][]string, cols, diags1, diags2 *[]bool) {
// 当放置完所有行时,记录解
if row == n {
newState := make([][]string, len(*state))
for i, _ := range newState {
newState[i] = make([]string, len((*state)[0]))
copy(newState[i], (*state)[i])
}
*res = append(*res, newState)
return
}
// 遍历所有列
for col := 0; col < n; col++ {
// 计算该格子对应的主对角线和次对角线
diag1 := row - col + n - 1
diag2 := row + col
// 剪枝:不允许该格子所在列、主对角线、次对角线上存在皇后
if !(*cols)[col] && !(*diags1)[diag1] && !(*diags2)[diag2] {
// 尝试:将皇后放置在该格子
(*state)[row][col] = "Q"
(*cols)[col], (*diags1)[diag1], (*diags2)[diag2] = true, true, true
// 放置下一行
backtrack(row+1, n, state, res, cols, diags1, diags2)
// 回退:将该格子恢复为空位
(*state)[row][col] = "#"
(*cols)[col], (*diags1)[diag1], (*diags2)[diag2] = false, false, false
}
}
}
/* 求解 n 皇后 */
func nQueens(n int) [][][]string {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
state := make([][]string, n)
for i := 0; i < n; i++ {
row := make([]string, n)
for i := 0; i < n; i++ {
row[i] = "#"
}
state[i] = row
}
// 记录列是否有皇后
cols := make([]bool, n)
diags1 := make([]bool, 2*n-1)
diags2 := make([]bool, 2*n-1)
res := make([][][]string, 0)
backtrack(0, n, &state, &res, &cols, &diags1, &diags2)
return res
}
/* 回溯算法: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
}
/* 回溯算法:n 皇后 */
function backtrack(row, n, state, res, cols, diags1, diags2) {
// 当放置完所有行时,记录解
if (row === n) {
res.push(state.map((row) => row.slice()));
return;
}
// 遍历所有列
for (let col = 0; col < n; col++) {
// 计算该格子对应的主对角线和次对角线
const diag1 = row - col + n - 1;
const 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 皇后 */
function nQueens(n) {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
const state = Array.from({ length: n }, () => Array(n).fill('#'));
const cols = Array(n).fill(false); // 记录列是否有皇后
const diags1 = Array(2 * n - 1).fill(false); // 记录主对角线上是否有皇后
const diags2 = Array(2 * n - 1).fill(false); // 记录次对角线上是否有皇后
const res = [];
backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
/* 回溯算法:n 皇后 */
function backtrack(
row: number,
n: number,
state: string[][],
res: string[][][],
cols: boolean[],
diags1: boolean[],
diags2: boolean[]
): void {
// 当放置完所有行时,记录解
if (row === n) {
res.push(state.map((row) => row.slice()));
return;
}
// 遍历所有列
for (let col = 0; col < n; col++) {
// 计算该格子对应的主对角线和次对角线
const diag1 = row - col + n - 1;
const 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 皇后 */
function nQueens(n: number): string[][][] {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
const state = Array.from({ length: n }, () => Array(n).fill('#'));
const cols = Array(n).fill(false); // 记录列是否有皇后
const diags1 = Array(2 * n - 1).fill(false); // 记录主对角线上是否有皇后
const diags2 = Array(2 * n - 1).fill(false); // 记录次对角线上是否有皇后
const res: string[][][] = [];
backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
/* 回溯算法:n 皇后 */
void backtrack(
int row,
int n,
List<List<String>> state,
List<List<List<String>>> res,
List<bool> cols,
List<bool> diags1,
List<bool> diags2,
) {
// 当放置完所有行时,记录解
if (row == n) {
List<List<String>> copyState = [];
for (List<String> sRow in state) {
copyState.add(List.from(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] = true;
diags1[diag1] = true;
diags2[diag2] = true;
// 放置下一行
backtrack(row + 1, n, state, res, cols, diags1, diags2);
// 回退:将该格子恢复为空位
state[row][col] = "#";
cols[col] = false;
diags1[diag1] = false;
diags2[diag2] = false;
}
}
}
/* 求解 n 皇后 */
List<List<List<String>>> nQueens(int n) {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
List<List<String>> state = List.generate(n, (index) => List.filled(n, "#"));
List<bool> cols = List.filled(n, false); // 记录列是否有皇后
List<bool> diags1 = List.filled(2 * n - 1, false); // 记录主对角线上是否有皇后
List<bool> diags2 = List.filled(2 * n - 1, false); // 记录次对角线上是否有皇后
List<List<List<String>>> res = [];
backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
/* 回溯算法:n 皇后 */
fn backtrack(
row: usize,
n: usize,
state: &mut Vec<Vec<String>>,
res: &mut Vec<Vec<Vec<String>>>,
cols: &mut [bool],
diags1: &mut [bool],
diags2: &mut [bool],
) {
// 当放置完所有行时,记录解
if row == n {
res.push(state.clone());
return;
}
// 遍历所有列
for col in 0..n {
// 计算该格子对应的主对角线和次对角线
let diag1 = row + n - 1 - col;
let diag2 = row + col;
// 剪枝:不允许该格子所在列、主对角线、次对角线上存在皇后
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
// 尝试:将皇后放置在该格子
state[row][col] = "Q".into();
(cols[col], diags1[diag1], diags2[diag2]) = (true, true, true);
// 放置下一行
backtrack(row + 1, n, state, res, cols, diags1, diags2);
// 回退:将该格子恢复为空位
state[row][col] = "#".into();
(cols[col], diags1[diag1], diags2[diag2]) = (false, false, false);
}
}
}
/* 求解 n 皇后 */
fn n_queens(n: usize) -> Vec<Vec<Vec<String>>> {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
let mut state: Vec<Vec<String>> = vec![vec!["#".to_string(); n]; n];
let mut cols = vec![false; n]; // 记录列是否有皇后
let mut diags1 = vec![false; 2 * n - 1]; // 记录主对角线上是否有皇后
let mut diags2 = vec![false; 2 * n - 1]; // 记录次对角线上是否有皇后
let mut res: Vec<Vec<Vec<String>>> = Vec::new();
backtrack(
0,
n,
&mut state,
&mut res,
&mut cols,
&mut diags1,
&mut diags2,
);
res
}
/* 回溯算法:n 皇后 */
void backtrack(int row, int n, char state[MAX_SIZE][MAX_SIZE], char ***res, int *resSize, bool cols[MAX_SIZE],
bool diags1[2 * MAX_SIZE - 1], bool diags2[2 * MAX_SIZE - 1]) {
// 当放置完所有行时,记录解
if (row == n) {
res[*resSize] = (char **)malloc(sizeof(char *) * n);
for (int i = 0; i < n; ++i) {
res[*resSize][i] = (char *)malloc(sizeof(char) * (n + 1));
strcpy(res[*resSize][i], state[i]);
}
(*resSize)++;
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, resSize, cols, diags1, diags2);
// 回退:将该格子恢复为空位
state[row][col] = '#';
cols[col] = diags1[diag1] = diags2[diag2] = false;
}
}
}
/* 求解 n 皇后 */
char ***nQueens(int n, int *returnSize) {
char state[MAX_SIZE][MAX_SIZE];
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
state[i][j] = '#';
}
state[i][n] = '\0';
}
bool cols[MAX_SIZE] = {false}; // 记录列是否有皇后
bool diags1[2 * MAX_SIZE - 1] = {false}; // 记录主对角线上是否有皇后
bool diags2[2 * MAX_SIZE - 1] = {false}; // 记录次对角线上是否有皇后
char ***res = (char ***)malloc(sizeof(char **) * MAX_SIZE);
*returnSize = 0;
backtrack(0, n, state, res, returnSize, cols, diags1, diags2);
return res;
}
/* 回溯算法:n 皇后 */
fun backtrack(
row: Int,
n: Int,
state: MutableList<MutableList<String>>,
res: MutableList<MutableList<MutableList<String>>?>,
cols: BooleanArray,
diags1: BooleanArray,
diags2: BooleanArray
) {
// 当放置完所有行时,记录解
if (row == n) {
val copyState = mutableListOf<MutableList<String>>()
for (sRow in state) {
copyState.add(sRow.toMutableList())
}
res.add(copyState)
return
}
// 遍历所有列
for (col in 0..<n) {
// 计算该格子对应的主对角线和次对角线
val diag1 = row - col + n - 1
val diag2 = row + col
// 剪枝:不允许该格子所在列、主对角线、次对角线上存在皇后
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
// 尝试:将皇后放置在该格子
state[row][col] = "Q"
diags2[diag2] = true
diags1[diag1] = diags2[diag2]
cols[col] = diags1[diag1]
// 放置下一行
backtrack(row + 1, n, state, res, cols, diags1, diags2)
// 回退:将该格子恢复为空位
state[row][col] = "#"
diags2[diag2] = false
diags1[diag1] = diags2[diag2]
cols[col] = diags1[diag1]
}
}
}
/* 求解 n 皇后 */
fun nQueens(n: Int): MutableList<MutableList<MutableList<String>>?> {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
val state = mutableListOf<MutableList<String>>()
for (i in 0..<n) {
val row = mutableListOf<String>()
for (j in 0..<n) {
row.add("#")
}
state.add(row)
}
val cols = BooleanArray(n) // 记录列是否有皇后
val diags1 = BooleanArray(2 * n - 1) // 记录主对角线上是否有皇后
val diags2 = BooleanArray(2 * n - 1) // 记录次对角线上是否有皇后
val res = mutableListOf<MutableList<MutableList<String>>?>()
backtrack(0, n, state, res, cols, diags1, diags2)
return res
}
### 回溯算法:n 皇后 ###
def backtrack(row, n, state, res, cols, diags1, diags2)
# 当放置完所有行时,记录解
if row == n
res << state.map { |row| row.dup }
return
end
# 遍历所有列
for col in 0...n
# 计算该格子对应的主对角线和次对角线
diag1 = row - col + n - 1
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
end
end
end
### 求解 n 皇后 ###
def n_queens(n)
# 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
state = Array.new(n) { Array.new(n, "#") }
cols = Array.new(n, false) # 记录列是否有皇后
diags1 = Array.new(2 * n - 1, false) # 记录主对角线上是否有皇后
diags2 = Array.new(2 * n - 1, false) # 记录次对角线上是否有皇后
res = []
backtrack(0, n, state, res, cols, diags1, diags2)
res
end
可视化运行
逐行放置 \(n\) 次,考虑列约束,则从第一行到最后一行分别有 \(n\)、\(n-1\)、\(\dots\)、\(2\)、\(1\) 个选择,使用 \(O(n!)\) 时间。当记录解时,需要复制矩阵 state 并添加进 res ,复制操作使用 \(O(n^2)\) 时间。因此,总体时间复杂度为 \(O(n! \cdot n^2)\) 。实际上,根据对角线约束的剪枝也能够大幅缩小搜索空间,因而搜索效率往往优于以上时间复杂度。
数组 state 使用 \(O(n^2)\) 空间,数组 cols、diags1 和 diags2 皆使用 \(O(n)\) 空间。最大递归深度为 \(n\) ,使用 \(O(n)\) 栈帧空间。因此,空间复杂度为 \(O(n^2)\) 。