n皇后问题(DFS) C++实现

cpp 复制代码
#include<iostream>
using namespace std;
const int N=20;
bool col[N],dg[N],udg[N];
int n;
char q[N][N];

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

int main(){
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++) q[i][j]='.';
    dfs(0);
}
相关推荐
橘子汽水1685 分钟前
Leetcode 128,49最长连续序列,字母异位词分组
java·算法·leetcode
mmmmath_37 分钟前
LeetCode.438.找到字符串中所有字母异位词
数据结构·算法·leetcode
Nil20812 分钟前
leetcode 22括号生成
算法·leetcode·深度优先
Navigator_Z16 分钟前
LeetCode //C - 1237. Find Positive Integer Solution for a Given Equation
c语言·算法·leetcode
啦啦啦啦啦zzzz30 分钟前
Appender抽象类的实现c++20
linux·服务器·c++·c++20
神仙别闹10 小时前
基于 C++ 实现两个有序链表序列的交集
java·c++·链表
政企项目老覃11 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水12 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR12 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论