1 #include <iostream> 2 using namespace std; 3 4 #define N 8 5 6 int a[N][N] = { 0 }; 7 8 bool judge(int a[][N],int b,int c)//b行 c列 9 { 10 11 for (int i = 0; i < N; i++)//判断行 12 { 13 if (a[b][i] == 1) 14 { 15 return false; 16 } 17 } 18 19 for (int j = 0; j < N; j++)//判断列 20 { 21 if (a[j][c] == 1) 22 { 23 return false; 24 } 25 } 26 27 int tempB = b; 28 int tempC = c; 29 30 while (tempB >= 1 && tempC < N-1) 31 { 32 tempB--; 33 tempC++; 34 35 if (a[tempB][tempC] == 1) 36 { 37 return false; 38 } 39 } 40 41 tempB = b; 42 tempC = c; 43 while (tempB < N-1 && tempC >= 1) 44 { 45 tempB++; 46 tempC--; 47 48 if (a[tempB][tempC] == 1) 49 { 50 return false; 51 } 52 } 53 54 tempB = b; 55 tempC = c; 56 while (tempB >= 1 && tempC >= 1) 57 { 58 tempB--; 59 tempC--; 60 61 if (a[tempB][tempC] == 1) 62 { 63 return false; 64 } 65 } 66 67 tempB = b; 68 tempC = c; 69 while (tempB < N-1 && tempC < N-1) 70 { 71 tempB++; 72 tempC++; 73 74 if (a[tempB][tempC] == 1) 75 { 76 return false; 77 } 78 } 79 80 return true; 81 } 82 83 void print() 84 { 85 for (int i = 0; i < N; i++) 86 { 87 for (int j = 0; j < N; j++) 88 { 89 cout << a[i][j] << " "; 90 } 91 cout << endl; 92 } 93 } 94 95 int count1 = 0; 96 97 void fun(int a[][N], int b)//b行,c列 98 { 99 if (b == N)//说明第七行已经放下了 100 { 101 print(); 102 cout << ++count1 << "种" << endl; 103 system("pause"); 104 return; 105 } 106 else 107 { 108 for (int i = 0; i < N; i++)//遍历列 109 { 110 if ( judge(a, b, i) ) 111 { 112 a[b][i] = 1; 113 fun(a, b + 1); 114 a[b][i] = 0; 115 } 116 } 117 } 118 } 119 120 int main() 121 { 122 fun(a, 0); 123 124 system("pause"); 125 return 0; 126 }