https://www.luogu.com.cn/problem/P1219
经典递归回溯问题,八个皇后要不同行,不同列,不同斜线,不同行列还好说,就是这个不同斜线怎么判断,这里就要去找规律。
可以发现在一条右斜线上即这样一条斜线 / 上,所有点的横坐标加纵坐标等于一个固定值,并且每条斜线上的值都不相同,所以我们可以用标记数组还标记右斜线,当我们选择另一个点时,不会再去选择这条斜线上的点。
还有左斜线即这样一条斜线 \ ,每条斜线上的点的横坐标减纵坐标等于一个固定值,由于可能出现负值,所以我们再在固定值上加上一个棋盘大小n去标记数组。
剩下的就是搜索的问题了,主要是利用递归回溯来枚举所有情况,每次深入试探,如果深搜到头就回溯,具体看代码理解
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <iomanip>
using namespace std;
int n, k;
int arr[1000];//记录解
int arr1[14];//记录列
int arr2[100];//记录左斜线
int arr3[100];//记录右斜线
int times;//记录次数
void dfs(int t) {//t代表行数
if (t > n) {//输出
if (times < 3) {
for (int i = 1; i <= n; i++)cout << arr[i] << " ";
cout << endl;
}
times++;
return;
}
for (int i = 1; i <= n; i++) {//i代表列数
if (!arr1[i]&&!arr2[i+t]&&!arr3[t-i+n]) {//该行该列该左斜线右斜线上都没有皇后
arr1[i] = 1;
arr2[i + t] = 1;
arr3[t - i + n] = 1;//标记行,列,斜线
arr[t] = i;//把解存入数组
dfs(t + 1);//深入
arr1[i] = 0;
arr2[i + t] = 0;
arr3[t - i + n] = 0;//回溯
}
}
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
cin >> n;
dfs(1);
cout << times << endl;
return 0;
}