DFS—n皇后

#include<iostream>
using namespace std;
int n;
int pos[10];
//pos[3]=4 第三行的放在第四列
bool check(int x,int k){
    //第x行能否放到第k列
    //前面的x-1行依次检查:第a行 放在pos[a]列
    for(int i=1; i<=x-1; i++){
        //对角线 或者放在了同一列(已经保证不在同一行)
        if(abs(k-pos[i])==abs(x-i)||pos[i]==k)
            return false;
    }
    return true;
}
void dfs(int x){
    if(x==n+1){
        for(int i=1; i<=n; i++){ //行
            for(int j=1; j<=n; j++){ //列
                if(pos[i]==j) cout << "Q";
                else cout << ".";
            }
            cout << endl;
        }
        cout << endl;
    }
    for(int i=1; i<=n; i++){
        if(check(x,i)){
            pos[x]=i;
            dfs(x+1);
        }
    }
}
int main(){
    cin >> n;
    dfs(1);
    return 0;
}
发布了30 篇原创文章 · 获赞 0 · 访问量 679

猜你喜欢

转载自blog.csdn.net/jhckii/article/details/104128954