[LeetCode]51. N-Queens

Problem

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 ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Example:

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.

Solution

Analysis

8皇后问题. 各个皇后不能在同一行,不能在同一列,同时也不能在同一条对角线(正or斜).

对角线可以通过集合方法判断. x+y=a, 或者 x-y=a. 也就是说点a和点b,对应坐标差的绝对值不能相等.

这里的一个问题是,原始排版是空的,需要将最终内容拼接出来,而不是在原始内容上修改个别位置. 另外,位置有效性判断条件,我们可以稍作修改,筛选掉一部分:去掉行. 因为每次放完一个皇后之后,下一个位置一定是下一行, 跳过本行.

回溯,或者说递归,最终要的是终止条件.这里的终止条件是行号i==n,表示最后一行已经排完了,终止END.

遍历时,在当前行所有列位置进行尝试.

Codes

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
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<pair<int, int>> pCur;
vector<string> cur;
vector<vector<string>> res;

if (n <= 0) return res;

helper(n, 0, pCur, cur, res);

return res;
}
private:
void helper(int n, int i,vector<pair<int, int>> &pCur, vector<string>& cur, vector<vector<string>>& res){
if (i == n){
res.push_back(cur);
return;
}
for (int j=0; j< n; j++){
bool valid = true;
pair<int, int> candidate = make_pair(i, j);// 可能的摆放位置

for (auto p: pCur){
if (isAttackable(p, candidate)){
valid = false;
break;
}
}
if (valid){//有效. 放入当前行
pCur.push_back(candidate);
string s(n, '.');
s[j] = 'Q';
cur.push_back(s);

helper(n, i+1, pCur, cur, res);

pCur.pop_back();
cur.pop_back();
}
}
}
bool isAttackable(const pair<int, int> &p1, const pair<int, int> &p2){// 有效性判断
if (p1.second == p2.second || abs(p1.first-p2.first) == abs(p1.second-p2.second))// 对角线判断
return true;
return false;
}
};
您的支持就是我更新的最大动力!谢谢!