N-Queens II
Q:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
A: 用N-Queens的方法,当n=12时,会超时。
下述方法,把可以放皇后的位置,直接计算出来,不需要每次遍历并判断。
void queens(int row,int ld,int rd,int upper,int& cnt) { if(row==upper) cnt++; else { int pos = upper&(~(row|ld|rd)); //pos中等于1的位置,表示可以放皇后的位置 while(pos) //pos==0,表示不可以放皇后了 { int p = pos&(-pos); // pos&(-pos) = pos&(~pos+1),表示取出取出最右边的那个1 pos = pos - p; queens(row+p,(ld+p)<<1,(rd+p)>>1,upper,cnt); } } } int totalNQueens(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int cnt = 0; if(n>0) { int upper = (1<<n)-1; queens(0,0,0,upper,cnt); } return cnt; }