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.
q is queens on same col
diagonal is queens on diagonal ways like ↘
anti diagonal is queens on reverse diagonal ways like ↙
check queen is available to put on board[cur][i] if (q | diagonal | antiDiagonal) & (1<<i) is not 0 it means queen is not possible to put on board[cur][i]
C++ code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { int res = 0;
intdfs(int n, int cur = 0, int q = 0, int diagonal = 0, int antiDiagonal = 0){ if(cur == n) return ++res; for(int i = 0; i < n; i++) { if((q & (1<<i)) || (diagonal & (1<<i)) || (antiDiagonal & (1<<i))) continue; dfs(n, cur + 1, q ^ (1<<i), (diagonal ^ (1<<i)) << 1, (antiDiagonal ^ (1<<i)) >> 1); } return res; } public: inttotalNQueens(int n){ returndfs(n); } };