05 August 2008
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens’ placement, where
and 1
'Q'
both indicate a queen and an empty space respectively.1
'.'
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
N皇后问题,棋盘上每一行每一列和每一斜线都不能都两个皇后;这道题是经典的回溯法,按照每一行遍历,每次加一个皇后,然后利用回溯法检查每一列和每个对角线是否已经有皇后了,有则回溯到前面一个状态,否则继续向下递归,直到最后一行的皇后放好就将结果加入到results里面。时间复杂度O(n^2),空间会创建一个记录每一行皇后所在的列的位置的一维数组,为O(n)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> results = new ArrayList<>();
if (n <= 0) {
return results;
}
// int[n]是记录每一行皇后所放的位置
// int[0]是第一行皇后的位置,int[1]是第二行皇后的位置...
dfs(results, 0, new int[n]);
return results;
}
//传入的参数是结果集,循环的行数,循环到该行-皇后所处的列的位置
private void dfs(List<List<String>> result, int index, int[] queenPositions) {
//递归的结束条件,找到一个结果
if (index == queenPositions.length) {
addOneSolution(result, queenPositions);
return;
}
// 逐行构建一个有效的放置方法
for (int i = 0; i < queenPositions.length; i++) {
queenPositions[index] = i; //每个位置都尝试,找到所有可能的组合
if (isValid(queenPositions, index)) {
dfs(result, index + 1, queenPositions);
}
}
}
private boolean isValid(int[] queenPositions, int index) {
for (int i = 0; i < index; i++) {
//剪枝,判断同一列中是否有重复的皇后
if (queenPositions[i] == queenPositions[index]) {
return false;
}
//判断对角线上是否有重复的皇后
if (Math.abs(queenPositions[index] - queenPositions[i]) == Math.abs(i - index)) {
return false;
}
}
return true;
}
// 根据每行皇后的位置构建结果并返回
private void addOneSolution(List<List<String>> result, int[] queens) {
List<String> oneResult = new ArrayList<>();
for (int queen : queens) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < queens.length; j++) {
if (queen == j) {
sb.append('Q');
} else {
sb.append('.');
}
}
oneResult.add(sb.toString());
}
result.add(oneResult);
}
}