N- Queens I I Algorithm
The eight queens puzzle is an example of the more general N queens problem of put N non-attacking queens on an n×n chessboard, for which solutions exist for all natural numbers N with the exception of N = 2 and N = 3.The eight queens puzzle is the problem of put eight chess queens on an 8×8 chessboard so that no two queens threaten each other; thus, a solution necessitates that no two queens share the same row, column, or diagonal. Chess composer Max Bezzel published the eight queens puzzle in 1848.Nauck also extended the puzzle to the N queens problem, with N queens on a chessboard of n×n squares. In 1874, S. Gunther proposed a method use determinants to find solutions.
class Solution {
public:
int totalNQueens(int n) {
int result = 0;
dfs(result, n, 0, 0, 0);
return result;
}
void dfs(int& result, int n, int col, int l, int r) {
int mask = (1 << n) - 1;
if (col == mask) {
result++;
} else {
int valid = mask & (~(col | l | r));
while (valid) {
int p = valid & (-valid);
valid -= p;
dfs(result, n, col + p, (l + p) << 1, (r + p) >> 1);
}
}
}
};