题目链接
https://www.acwing.com/problem/content/description/845/
思路
我们每一层只需要搜一个,然后判断一下这一层的这个点的列、左斜线、右斜线是否被搜过,如果没有被搜过那么就往下搜,然后归的过程记得回溯,最后搜到第N层的时候就直接输出这种情况即可
#include<bits/stdc++.h>
using namespace std;
//----------------自定义部分----------------
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
int dx[4]={0,-1,0,1},dy[4]={-1,0,1,0};
ll ksm(ll a,ll b) {
ll ans = 1;
for(;b;b>>=1LL) {
if(b & 1) ans = ans * a % mod;
a = a * a % mod;
}
return ans;
}
ll lowbit(ll x){return -x & x;}
const int N = 30;
//----------------自定义部分----------------
int n,m,q,col[N],dg[N],udg[N];
//dg存储的是从左上往右下这斜线,udg则是存储的从右上往左下的这条斜线
char g[N][N];
void dfs(int step){
if(step == n){
for(int i = 0;i < n; ++i) cout<<g[i]<<endl;
cout<<endl;
return;
}
for(int i = 0;i < n; ++i) {
if(!col[i] && !dg[step+i] && !udg[n-step+i]) {
g[step][i] = 'Q';
col[i] = dg[step+i] = udg[n-step+i] = 1;
dfs(step+1);
col[i] = dg[step+i] = udg[n-step+i] = 0;
g[step][i] = '.';
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
cin>>n;
for(int i = 0;i < n; ++i)
for(int j = 0;j < n; ++j)
g[i][j] = '.';
dfs(0);
return 0;
}