八皇后-DFS经典

10 篇文章 0 订阅

DFS和BFS其实学的很早,但是DFS我一直很菜

在这里插入图片描述


题目链接:洛谷P1219 传送门

在这里插入图片描述
在这里插入图片描述


众所周知(In my opinion),八皇后是学DFS必刷的题,然而,本蒟蒻到今天才写。


题目很简单,就是经典八皇后,只不过让你输出字典序最小的三个解,然后再输出总共有几种解。

很简单,我们开四个数组a,b,c,d分别用来记录行、列、左上到右下,右下到左上这四种方向上皇后的占领情况,由题意,a数组直接记录该行皇后的位置,其他三个数组只需标记即可

代码:

#include <stdio.h>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <deque>
#include <cstring>
#include <iterator>
#include <set>
#include <map>
using namespace std;
#define ll long long
int a[100], b[100], c[100], d[100];
//分别表示行、列、左上到右下,左下到右上的皇后占领情况
int n;
int ans;
void print()
{
    if (ans < 3)//输出前三个解
    {
        printf("%d", a[1]);
        for (int i = 2; i <= n; i++)
            printf(" %d", a[i]);
        cout << endl;
    }
    ans++;
}
void queen(int x)
{
    if (x > n)
    {
        print();
        return;
    }
    for (int i = 1; i <= n; i++)
    {
        if ((!b[i]) && (!c[n + x - i]) && (!d[i + x - 1]))
        //如果该位置未被占领
        {
            b[i] = 1;
            c[n + x - i] = 1;
            d[i + x - 1] = 1;
            a[x] = i;
            queen(x + 1);
            b[i] = 0;
            c[n + x - i] = 0;
            d[i + x - 1] = 0;
        }
    }
}
int main()
{
    cin >> n;
    queen(1);
    cout << ans << endl;
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hesorchen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值