dfs has also been mentioned before, if you are interested, you can click the blue word -> dfs full arrangement
Let's draw a picture to simulate the process first (computer drawing is not very good, so let's do it by hand)
conditions are met
Condition: Any two queens cannot be in the same row, column or slash
deal with:
Same line: process the next line every time Q is finished
The same column: marked with line[l]
Same slash: Q is not placed in dg[n-l+r] and udg[l+r]
Code demo:
#include<iostream>
using namespace std;
const int N=10;
//标记两条斜线上和列上对应的点是否有皇后
int dg[2*N],udg[2*N],line[N],n;
char a[N][N];//用二维数组表棋盘
void dfs(int r)
{
if(r==n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j];
}
cout<<endl;
}
cout<<endl;
return;
}
for(int l=0;l<n;l++)
{
if(!dg[n-l+r]&&!udg[l+r]&&!line[l])
{
a[r][l]='Q';
dg[n-l+r]=udg[l+r]=line[l]=1;
//标记对应的斜线和列上已经有了皇后
dfs(r+1);//到下一行
dg[n-l+r]=udg[l+r]=line[l]=0;//清除标记
a[r][l]='.';//重置棋盘
}
}
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]='.';
}
}
dfs(0);
return 0;
}