Leetcode 52. N-Queens II (Hard) (cpp)
Tag: Backtracking
Difficulty: Hard
/*
52. N-Queens II (Hard)
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
*/
class Solution {
public:
int totalNQueens(int n) {
int res;
vector<int> res_sub;
unordered_map<int, bool> v;
unordered_map<int, bool> u;
unordered_map<int, bool> d;
solve(res, res_sub, n, v, u, d);
return res;
}
private:
void solve(int& res, vector<int>& res_sub, int size, unordered_map<int, bool>& v, unordered_map<int, bool>& u, unordered_map<int, bool>& d) {
if (res_sub.size() == size) {
res++;
return;
}
for (int i = 0; i < size; i++) {
if (valid(res_sub.size(), v, u, d, i)) {
res_sub.push_back(i);
solve(res, res_sub, size, v, u, d);
res_sub.pop_back();
back(res_sub.size(), v, u, d, i);
}
}
}
bool valid(int col, unordered_map<int, bool>& v, unordered_map<int, bool>& u, unordered_map<int, bool>& d, int row) {
if (v[row] == false && u[row - col] == false && d[row + col] == false) {
v[row] = true;
u[row - col] = true;
d[row + col] = true;
return true;
}
return false;
}
void back(int col, unordered_map<int, bool>& v, unordered_map<int, bool>& u, unordered_map<int, bool>& d, int row) {
v[row] = false;
u[row - col] = false;
d[row + col] = false;
}
};