0
点赞
收藏
分享

微信扫一扫

acwing自我学习笔记--n-皇后问题 843

奋斗De奶爸 2022-02-15 阅读 57

#include <iostream>
#include <cstring>
using namespace std;

const int N = 10;
char g[N][N];//棋盘
int col[N],dg[N*2], udg[N*2];
int n;

void DFS(int x)
{
    if (x == n)//已放置n个皇后了
    {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                cout << g[i][j];
            }
            cout << endl;
        }
        cout << endl;
        return;
    }

    for (int y = 0; y < n; y++)//从列开始
    {
        if (!col[y] && !dg[y + x] && !udg[y-x+n])
        {
            col[y] = dg[y + x] = udg[y-x+n] = true;
            g[x][y] = 'Q';
            DFS(x + 1);//下一行
            col[y] = dg[y + x] = udg[y-x + n] = false;
            g[x][y] = '.';
        }
    }
}

int main()
{
    cin >> n;
    memset(g, '.', sizeof(g));//棋盘初始化
    DFS(0);//从第一行开始遍历
    return 0;
}

举报

相关推荐

0 条评论