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.
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.."]
]
题解:
比之前还简单,直接输出答案个数即可。
class Solution {
public:
void dfs(int &res, vector<vector<bool>> &chess, int n, int i) {
if (i == n) {
res++;
}
else {
for (int j = 0; j < n; j++) {
if (chess[i][j] == true && checkPos(chess, n, i, j) == true) {
chess[i][j] = false;
dfs(res, chess, n, i + 1);
chess[i][j] = true;
}
}
}
}
bool checkPos(vector<vector<bool>> &chess, int n, int x, int y) {
bool res = true;
for (int i = 0; i < n; i++) {
if (i == x) {
continue;
}
res &= chess[i][y];
}
int left = x - 1, right = x + 1, up = y - 1, down = y + 1;
while (left >= 0 && up >= 0) {
res &= chess[left--][up--];
}
while (right < n && down < n) {
res &= chess[right++][down++];
}
left = x - 1, right = x + 1, up = y - 1, down = y + 1;
while (left >= 0 && down < n) {
res &= chess[left--][down++];
}
while (right < n && up >= 0) {
res &= chess[right++][up--];
}
return res;
}
int totalNQueens(int n) {
int res = 0;
vector<vector<bool>> chess(n, vector<bool>(n, true));
dfs(res, chess, n, 0);
return res;
}
};