题解 | #N皇后问题#

思路

考察递归,枚举皇后的位置,不符合条件回溯即可

#include <bits/stdc++.h>
#define ios std::ios::sync_with_stdio(false);std::cin.tie(0)
using namespace std;
int res[20],cot,n;
void dfs(int L,int C){
    if(L == n) cot++;
    else{
        res[L] = C;
        for(int i = 1;i <= n;i++){
            int j;
            for(j = 1;j <= L;j++)
                if((res[j] == i)||((j+res[j]) == L+1+i)||((j-res[j]) == (L+1-i)))
                    break;
            if(j == L+1) dfs(L+1,i);
        }
    }
}

int main(){
    ios;
    cin>>n;
    for(int i = 1;i <= n;i++)
        dfs(1,i);
    cout<<cot;
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务