[LeetCode]52. N-Queens II

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 the number of distinct solutions to the n-queens puzzle.

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

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

Solution

Analysis

这道题的解法和51题相同,都是使用回溯法. 只不过这里,不需要记录所有可能的解,仅仅需要返回解的个数即可. 偷懒的话,可以直接使用上一题的解法,最后返回可能解的个数,也就是数组的容量大小.

这里,只需要返回可能解的个数, 所以不需要记录所有可能的解,仅仅需要一个可变的统计量count, 同时一个数组记录之前皇后的摆放位置, 这里使用pair结构来记录每个皇后的坐标(二维[x, y]). 具体代码如下:

Code

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
class Solution {
public:
int totalNQueens(int n) {
vector<pair<int, int>> points;
int count = 0;

dfs(n, 0, points, count);

return count;
}
private:
bool isAttack(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;
}
void dfs(int n, int i, vector<pair<int, int>>& points, int &count){
if (i == n){
++count;
return;
}

for (int j=0; j< n; ++j){
pair<int, int> candidate = make_pair(i, j);
bool isValid = true;

for(auto p: points){
if (isAttack(p, candidate)){
isValid = false;
break;
}
}

if (isValid){
points.push_back(candidate);

dfs(n, i+1, points, count);

points.pop_back();// 回溯
}
}
}
};
您的支持就是我更新的最大动力!谢谢!