八皇后

题解:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 bool d[100]; // 记录棋盘主对角线能否放 5 bool c[100]; // 副对角线 6 bool b[20]; // 列 7 8 int a[20]; 9 10 // 设queen在(i, j) //i为列标 ,j为行标 11 // 则vis[i - j + n] = 1 主对角线//+n是为了防止出现负数 12 // vis[i + j] = 1 副对角线 13 // vis[i] = 1 列 14 // vis[j] = 1 行 15 16 /* 17 \ i 1 2 3 4 18 j \ 19 1 20 2 21 3 22 4 23 */ 24 25 int n; 26 void print() 27 { 28 for (int j = 1; j <= n; ++j) 29 { 30 for (int i = 1; i <= n; ++i) 31 { 32 if (a[j] == i) 33 cout << 'Q'; 34 else 35 cout << '.'; 36 } 37 cout << endl; 38 } 39 puts(""); 40 } 41 42 void dfs(int j) // j表示行 (从第一行开始dfs) (因为一行最多只能放一个皇后) 43 { 44 if (j > n) 45 { 46 print(); 47 return; 48 } 49 50 for (int i = 1; i <= n; ++i) 51 { 52 if (b[i] == 0 && c[i + j] == 0 && d[i - j + n] == 0) 53 { 54 a[j] = i; 55 b[i] = 1; 56 c[i + j] = 1; 57 d[i - j + n] = 1; 58 59 dfs(j + 1); 60 61 // 回溯 62 b[i] = 0; 63 c[i + j] = 0; 64 d[i - j + n] = 0; 65 } 66 } 67 } 68 69 int main() 70 { 71 cin >> n; 72 dfs(1); 73 return 0; 74 }

题解:
这题和上面一题基本一样,就是先把结果都存数组里,然后再改一些细节
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int N = 40; 4 bool b[N], c[N], d[N]; 5 int a[N]; 6 int n = 8, t; 7 int cnt = 0; 8 char s[100][15][15] = {0}; 9 10 void print() 11 { 12 for (int j = 1; j <= n; ++j) 13 { 14 for (int i = 1; i <= n; ++i) 15 if (a[j] == i) 16 cout << i; 17 } 18 cout << endl; 19 } 20 21 void copy() 22 { 23 ++cnt; 24 for (int j = 1; j <= n; ++j) 25 { 26 for (int i = 1; i <= n; ++i) 27 { 28 if (a[j] == i) 29 s[cnt][j][i] = 'Q'; 30 else 31 s[cnt][j][i] = '0'; 32 } 33 } 34 } 35 36 void dfs(int j) 37 { 38 if (j > n) 39 { 40 copy(); 41 return; 42 } 43 44 for (int i = 1; i <= n; ++i) 45 { 46 if (!b[i] && !c[i - j + n] && !d[i + j]) 47 { 48 a[j] = i; 49 b[i] = 1; 50 c[i - j + n] = 1; 51 d[i + j] = 1; 52 53 dfs(j + 1); 54 55 b[i] = 0; 56 c[i - j + n] = 0; 57 d[i + j] = 0; 58 } 59 } 60 } 61 62 int main() 63 { 64 cin >> t; 65 dfs(1); 66 while (t--) 67 { 68 int tmp; 69 cin >> tmp; 70 for (int i = 1; i <= n; ++i) 71 { 72 for (int j = 1; j <= n; ++j) 73 { 74 if (s[tmp][i][j] == 'Q') 75 { 76 cout << j; 77 } 78 } 79 } 80 cout << endl; 81 } 82 return 0; 83 }

浙公网安备 33010602011771号