假期稍微回顾一下一些经典问题的写法
说明:
N皇后问题遍历的话太耗时间,因此使用回溯法解决
代码
#include <cstdio>
#include <cmath>
#include <iostream>
#define ll long long
using namespace std;
const int maxn = 16;
bool hashtable[maxn] = {0};
int n, cnt = 0, P[maxn] = {0};
// 生成第index列的皇后行数
void generateP(int index) {
// 递归出口 表示找到了正确解
if (index == n+1) {
cnt ++;
return;
}
// 遍历n行
for (int i = 1; i <= n; i ++) {
// 如果第i行没有被占用过
if (!hashtable[i]) {
// flag=true表示放在第i行不会冲突
bool flag = true;
// 遍历检查之前列的皇后位置
for (int pre = 1; pre < index; pre ++) {
// 如果有对角则矛盾退出循环
if (abs(index-pre) == abs(i-P[pre])) {
flag = false;
break;
}
}
// 可以放在第index列的第i行
if (flag) {
P[index] = i; // 存储位置
hashtable[i] = true;
generateP(index+1); // 继续递归
hashtable[i] = false;
}
}
}
}
int main() {
cin >> n;
generateP(1);
cout << cnt << endl;
}
总结
学习不息,继续加油