#include<iostream> #include<vector> #include<math.h> #include<stdio.h> using namespace std; int temp = 0; int place(int k, vector<int>& x) { for (int i = 1; i < k; i++) if (x[k] == x[i] || fabs(k - i) == fabs(x[k] - x[i])) return 1; return 0; }int queens(int i, vector<int>&x,int n) { if (i > n) { #if 0 for (int k = 1; k <= n; k++) cout << x[k]; cout << "\n"; #endif } else for (int j = 1; j <= n; j++) { x[i] = j; if (place(i, x) == 0) queens(i + 1, x, n); } } int main() { int z; cin >> z; int n; for (int i = 1; i <= z; i++) { cin >> n; vector<int>x(n + 1); int begin = clock(); int flag = queens(1, x, n); int end = clock(); cout << flag; cout << "\n"; } }以上代码要求增加输出解的个数
时间: 2024-03-21 21:43:02 浏览: 94
可以在 queens 函数中增加一个计数器,记录找到的解的个数,然后在 main 函数中输出即可。修改后的代码如下:
```c++
#include<iostream>
#include<vector>
#include<math.h>
#include<stdio.h>
using namespace std;
int temp = 0;
int place(int k, vector<int>& x) {
for (int i = 1; i < k; i++)
if (x[k] == x[i] || fabs(k - i) == fabs(x[k] - x[i]))
return 1;
return 0;
}
int queens(int i, vector<int>& x, int n, int& count) {
if (i > n) {
#if 0
for (int k = 1; k <= n; k++)
cout << x[k];
cout << "\n";
#endif
count++; // 找到一个解,计数器加一
} else {
for (int j = 1; j <= n; j++) {
x[i] = j;
if (place(i, x) == 0)
queens(i + 1, x, n, count);
}
}
return count;
}
int main() {
int z;
cin >> z;
int n;
for (int i = 1; i <= z; i++) {
cin >> n;
vector<int> x(n + 1);
int begin = clock();
int count = 0; // 初始化计数器
queens(1, x, n, count);
int end = clock();
cout << count << "\n"; // 输出解的个数
}
return 0;
}
```
阅读全文