首页 > 其他 > 详细

八皇后问题(dfs)(回溯)

时间:2021-04-03 20:00:07      阅读:24      评论:0      收藏:0      [点我收藏+]
//思路:采用一维的方式
//搜索每一行,从左到右,逐个查看其是否符合于当前的规范
//对于一个二维的空间图,一个位置上,对角线上的坐标,x+y等于一个定值
//或者x-y+n会是一个定值
#include <iostream> #include <set> #include <vector> #include <cmath> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #define ll long long using namespace std; const int M = 1e3 + 1; int a[M], b[M], c[M], d[M];//a表示当前存储的数据,b表示当前的位置是否用到过,c表示主对角线,d表示副对角线 int n; int ans;//存储已经找到了几个图 void print() { ans++; if (ans <= 3) {//找到小于三个的情况下 for (int i = 1; i <= n; i++) cout << a[i] << " "; cout << endl; } } inline int dfs(int i) { for (int j = 1; j <= n; j++) { if (b[j] == 0 && c[i + j] == 0 && d[i - j + n] == 0) {//当前位置没用过,且对角线上的位置没用过 a[i] = j;//直接存储当前的位置,即i行拿了第j个位置 b[j] = 1; c[i + j] = 1; d[i - j + n] = 1; if (i == n) print(); else dfs(i + 1);//搜索下一行
        //回溯,因为是在同一个j循环里,i是不变的,所以a数组不用回溯,下次直接还是同样位置,赋值另一个j值
        //仅b,c,d数组需要回溯
b[j]
= 0; c[i + j] = 0; d[i - j + n] = 0; } } } int main() { cin >> n; dfs(1);//从第一行开始,直接采用一维的做法 cout << ans << endl; return 0; }

 

八皇后问题(dfs)(回溯)

原文:https://www.cnblogs.com/BlogBaudelaire/p/14613600.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!