# include <stdio.h>
# include <stdlib.h>
char cols;//1个字节8位,1为该列有皇后0为没有
short l_slash;//2个字节16位,1为该斜线有皇后0为没有
short r_slash;//2个字节16位,1为该斜线有皇后0为没有
int count;
void NQueens(int n);
void Place(int flag[], char cols, short l_slash, short r_slash, int row);
void Show(int flag[]);
int main(void){
//flag存放的值为下标所在行所放置皇后的列号
int * flag = (int*)calloc(8, sizeof(int));
Place(flag, cols, l_slash, r_slash, 0);
printf("8-queen has %d ways\n", count);
free(flag);
system("pause");
return 0;
}
void Place(int flag[], char cols, short l_slash, short r_slash, int row){
if(row == 8){
count++;
Show(flag);
return;
}
for(int col = 0; col < 8; col++){
int i = 1<<col;
if((cols & i)!= 0) continue;
int j = 1<<(row+col);
if((l_slash & j)!= 0) continue;
int k = 1<<(row-col+7);
if((r_slash & k)!= 0) continue;
flag[row] = col;
//将对应位设为1
cols |= i;
l_slash |= j;
r_slash |= k;
Place(flag, cols, l_slash, r_slash, row+1);
//将对应位设为0
cols &= ~i;
l_slash &= ~j;
r_slash &= ~k;
}
}
void Show(int flag[]){
printf("No:%d\n", count);
for(int row = 0; row < 8; row++){
for(int col = 0; col < 8; col++){
if(flag[row] == col)
printf("1 ");
else
printf("0 ");
}
printf("\n");
}
printf("\n");
}
04-05
2006
10-28
1166
10-31
902