
#include <stdio.h>#include<stdbool.h>// 全局变量int place[8] = { 0 }; // 保存皇后的位置,下标为行,储存的数据为列。bool flag[8] = { 1, 1, 1, 1, 1, 1, 1, 1 }; // 用来保存哪一列已经存在皇后 bool d1[15] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 从左上到右下的对角线为上对角线,每条上对角线上的行和列的差是一样的。bool d2[15] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 从左下到右下的对角线为下对角线,每条下对角线上的行和列的和是一样的。int number = 0; // 统计解的数量// 函数声明void QueenVIII(int); // 八皇后问题void output(void); // 输出// 主函数int main(void){ //output(); QueenVIII(0); return 1;}void QueenVIII(int n) { int col; for (col = 0; col < 8;col++) { if (flag[col] && d1[n - col + 7] && d2[n + col]) { place[n] = col; flag[col]=false; d1[n - col + 7]=false; d2[n + col]=false; if (n < 7) QueenVIII(n + 1); else output(); flag[col] =1; d1[n - col + 7] =1; d2[n + col] =1; } }}void output(void) { int tablet[8][8] = {0}; int i, j, n; number++; printf("第%d种方法",number); printf("\n"); for (n = 0; n < 8; n++) tablet[n][place[n]] = 1; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { printf("%d ", tablet[i][j]); } printf("\n"); }}