大意略。
位运算求N皇后问题是目前最快的求解N皇后问题解法之一。
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
#define all (1<<n)-1
int n;
void dfs(int row, int ld, int rd, int &ans)
{
int p, pos;
if(row == all) { ans++; return ; }
pos = all & (~(row | ld | rd)); //求所有可能放皇后的位置
while(pos)
{
p = pos & (~pos+1); //求最右边的1
pos -= p;
dfs(row | p, (ld | p)<<1, (rd | p)>>1, ans);
}
return ;
}
int main()
{
while(~scanf("%d", &n) && n)
{
int ans = 0;
dfs(0, 0, 0, ans);
printf("%d\n", ans);
}
return 0;
}