#include <stdio.h>
int SIZE, MASK, COUNT;
void Backtrack(int y, int left, int down, int right)
{
int bitmap, bit;
if (y == SIZE) {
COUNT++;
} else {
bitmap = MASK & ~(left | down | right);
while (bitmap) {
bit = -bitmap & bitmap;
bitmap ^= bit;
Backtrack(y+1, (left | bit)<<1, down | bit, (right | bit)>>1);
}
}
}
int main(void)
{
SIZE = 10; /* <- N */
COUNT = 0; /* result */
MASK = (1 << SIZE) - 1;
Backtrack(0, 0, 0, 0);
printf("N=%d -> %d\n", SIZE, COUNT);
return 0;
}
- - - - - Q - - 00000100 0: Start - - - Q - - - - 00010000 1: | - - - - - - Q - 00000010 2: | Q - - - - - - - 10000000 3: | Back Tracking - - - - - - - Q 00000001 4: | - Q - - - - - - 01000000 5: | - - - - Q - - - 00001000 6: |/ - - Q - - - - - 00100000 7: Last
- - - - Q 0 - - Q - - 2 Q - - - - 4 ---> 0 2 4 1 3 (Unique judgment value) - - - Q - 1 - Q - - - 3
X X X - - - X X X - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
X X X - X Q - Q - - X - - - - - X - - - - - X - - - - - - - - - - - - -
X X X X x Q X X X - - - x x x X C - - x - x - x - - x - - x - - - x - - - x - - x - - - - x - A X - - - - x - X X X B - - x X X
90-degree rotation. (A) 180-degree rotation. (B) 270-degree rotation. (C)
If first queen is in the corner.
Total Solutions = Unique Solutions X 8.
If first queen is inside.
If 90-degree rotation is same pattern as the original.
Total Solutions = Unique Solutions X 2.
Else if 180-degree rotation is same pattern as the original.
Total Solutions = Unique Solutions X 4.
Else
Total Solutions = Unique Solutions X 8.
<------ N-Queens Solutions -----> <---- time ----> N: Total Unique days hh:mm:ss.-- 2: 0 0 0.00 3: 0 0 0.00 4: 2 1 0.00 5: 10 2 0.00 6: 4 1 0.00 7: 40 6 0.00 8: 92 12 0.00 9: 352 46 0.00 10: 724 92 0.00 11: 2680 341 0.00 12: 14200 1787 0.00 13: 73712 9233 0.06 14: 365596 45752 0.16 15: 2279184 285053 0.88 16: 14772512 1846955 5.93 17: 95815104 11977939 40.76 18: 666090624 83263591 4:55.50 19: 4968057848 621012754 37:49.96 20: 39029188884 4878666808 5:03:35.16 21: 314666222712 39333324973 1 18:40:00.09 CPU = Athlon XP 2100+ (1.73GHz) Compiler = Visual C++ 5.0