n皇后问题

文章介绍了两种不同的C++编程方法来解决N皇后问题:一种是按行进行全排列并使用深度优先搜索剪枝,另一种是对每个格子进行选择性放置皇后,采用回溯法。两种方法都涉及了二维数组和布尔变量的使用。
摘要由CSDN通过智能技术生成

第一种搜索方式:

按行进行全排列,边排列边剪枝,col,dg,udg(列,对角线,反对角线)

对角线和反对角线有2*n-1个,数组要多开

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 10;

int n;
char g[N][N];
bool col[N], dg[N*2], udg[N*2];

void dfs(int u)
{
    if (u == n)
    {
        for (int i = 0; i < n; i ++) puts(g[i]);
        puts("");
        return;
    }
    
    for (int i = 0; i < n; i ++)
    {
        if (!col[i] && !dg[i+u] && !udg[i-u+n])
        {
            g[u][i] = 'Q';
            col[i] = dg[i+u] = udg[i-u+n] = true;
            dfs(u+1);
            col[i] = dg[i+u] = udg[i-u+n] = false;
            g[u][i] = '.';
        }
    }
}
int main()
{
    cin >> n;
    for (int i = 0; i < n; i ++)
        for (int j = 0; j < n; j ++)
            g[i][j] = '.';
            
    dfs(0);
    
    return 0;
}

第二种搜索方式:

对每个格子进行选择加不加入皇后,当进行到最后一行的时候检查是否有n个皇后

#include <iostream>

using namespace std;

const int N = 10;

int n;
bool row[N], col[N], dg[N * 2], udg[N * 2];
char g[N][N];

void dfs(int x, int y, int s)
{
    if (s > n) return;
    if (y == n) y = 0, x ++ ;

    if (x == n)
    {
        if (s == n)
        {
            for (int i = 0; i < n; i ++ ) puts(g[i]);
            puts("");
        }
        return;
    }

    g[x][y] = '.';
    dfs(x, y + 1, s);

    if (!row[x] && !col[y] && !dg[x + y] && !udg[x - y + n])
    {
        row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;
        g[x][y] = 'Q';
        dfs(x, y + 1, s + 1);
        g[x][y] = '.';
        row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;
    }
}

int main()
{
    cin >> n;

    dfs(0, 0, 0);

    return 0;
}

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值