八皇后
1 #include<stdio.h> 2 int count = 0; 3 FILE *fp; 4 5 int notDanger(int row,int j,int (*chess)[8]) { 6 int i,k,flag1 =0,flag2=0,flag3=0,flag4=0,flag5=0,flag6=0; 7 //判断列方向 8 for (i = 0; i<8; i++) { 9 if(*(*(chess+i)+j) !=0) { 10 flag1=1; 11 break; 12 } 13 } 14 //判断左上方 15 for (i = row , k = j; i>=0 && k>=0 ; i--,k--) { 16 if(*(*(chess+i)+k) != 0) { 17 flag2 = 1; 18 break; 19 } 20 } 21 22 //判断右下方 23 for (i = row , k = j; i<8 && k<8 ; i++,k++) { 24 if(*(*(chess+i)+k) != 0) { 25 flag3 = 1; 26 break; 27 } 28 } 29 30 31 //判断右上方 32 for (i = row , k = j; i>=0 && k<8 ; i--,k++) { 33 if(*(*(chess+i)+k) != 0) { 34 flag4 = 1; 35 break; 36 } 37 } 38 39 40 //判断左下方 41 for (i = row , k = j; i<8 && k>=0 ; i++,k--) { 42 if(*(*(chess+i)+k) != 0) { 43 flag5 = 1; 44 break; 45 } 46 } 47 if( flag1 || flag2 || flag3 || flag4 || flag5) { 48 return 0; 49 } 50 else { 51 return 1; 52 } 53 54 } 55 56 void EightQueen(int row,int n,int(*chess)[8]) { 57 int chess2[8][8]; 58 int i,j; 59 for ( i= 0 ; i<8 ; i++) { 60 for (j=0; j<8; j++){ 61 chess2[i][j] = chess[i][j]; 62 } 63 } 64 if(8 == row) { 65 printf("第 %d 种\n",count+1); 66 fprintf(fp,"第 %d 种\n",count+1); 67 for (i=0 ; i<8 ; i++) { 68 for (j=0; j<8 ; j++) { 69 printf("%d ", *(*(chess2+i)+j)); 70 fprintf(fp,"%d ", *(*(chess2+i)+j)); 71 } 72 printf("\n"); 73 fprintf(fp,"\n"); 74 } 75 printf("\n"); 76 fprintf(fp,"\n"); 77 count++; 78 } 79 80 else { 81 for (j=0; j<n; j++) { 82 if(notDanger(row,j,chess)) { 83 for(i = 0 ; i<8 ; i++) { 84 *(*(chess2+row)+i) =0; 85 } 86 *(*(chess2+row)+j) = 1; 87 88 EightQueen(row+1,n,chess2); 89 } 90 } 91 92 } 93 94 } 95 96 int main() { 97 int chess[8][8]; 98 int i,j; 99 fp = fopen("EightQueen.txt","w+a+"); 100 for (i= 0 ; i<8 ; i++) { 101 for (j=0; j<8; j++){ 102 chess[i][j] = 0; 103 } 104 } 105 EightQueen(0, 8, chess); 106 107 printf("共有%d方案",count); 108 fprintf(fp,"共有%d方案",count); 109 fclose(fp); 110 111 112 return 0; 113 }