# 52. N-Queens II

The n-queens puzzle is the problem of placing `n` queens on an `n x 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 1:

``````Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
``````

Example 2:

``````Input: n = 1
Output: 1
``````

Constraints:

• `1 <= n <= 9`

``````class Solution {
public:
int totalNQueens(int n) {
int res = 0;
vector<int> pos(n, -1);
dfs(pos, 0, res);
return res;
}
void dfs(vector<int>& pos, int row, int& res) {
int n = pos.size();
if (row == n) {
++res;
return;
}
for (int col = 0; col < n; ++col) {
if (isValid(pos, row, col)) {
pos[row] = col;
dfs(pos, row + 1, res);
pos[row] = -1;
}
}
}
bool isValid(vector<int>& pos, int row, int col) {
for (int i = 0; i < row; ++i) {
if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {
return false;
}
}
return true;
}
};
``````

``````class Solution {
public:
int totalNQueens(int n) {
int res = 0;
vector<bool> cols(n), diag(2 * n), anti_diag(2 * n);
dfs(n, 0, cols, diag, anti_diag, res);
return res;
}
void dfs(int n, int row, vector<bool>& cols, vector<bool>& diag, vector<bool>& anti_diag, int& res) {
if (row == n) {
++res;
return;
}
for (int col = 0; col < n; ++col) {
int idx1 = col - row + n, idx2 = col + row;
if (cols[col] || diag[idx1] || anti_diag[idx2]) continue;
cols[col] = diag[idx1] = anti_diag[idx2] = true;
dfs(n, row + 1, cols, diag, anti_diag, res);
cols[col] = diag[idx1] = anti_diag[idx2] = false;
}
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/52

N-Queens

Grid Illumination

https://leetcode.com/problems/n-queens-ii/

https://leetcode.com/problems/n-queens-ii/discuss/20058/Accepted-Java-Solution

https://leetcode.com/problems/n-queens-ii/discuss/20048/Easiest-Java-Solution-(1ms-98.22)

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation