用位运算解n皇后问题

 

#include
#include

using namespace std;

int sum, n;

void Queen(int row, int ld, int rd)
{
int pos, p;

int upperlim = (1 << n) - 1;

if (row != upperlim)
{
pos = upperlim & ~(row | ld | rd);

while (pos != 0)
{
p = pos & -pos;

pos -= p;

Queen(row + p, (ld + p) <> 1);
}
}
else ++sum;
}

int main()
{
int ans[11], i;

for (i=1; i<=10; ++i)
{
sum = 0;

n = i;

Queen(0, 0, 0);

ans[i] = sum;
}

while (scanf("%d", &n), n)
{
printf("%d\n", ans[n]);
}

return 0;
}

你可能感兴趣的:(用位运算解n皇后问题)