Title description
Those who can play chess know very well: the queen can take any other pieces on the horizontal, vertical, and diagonal lines without a limit. How to put 8 queens on the board (there are 8 * 8 squares) so that none of them can be eaten! This is the famous Eight Queens problem.
enter
An integer n (1 <= n <= 10)
Output
Each line of output corresponds to a scheme, and all schemes are output in lexicographic order. Each scheme outputs the column number of the queen in order, separated by a space between two adjacent numbers. If there is no set of feasible solutions, output "no solute!"
Sample input Copy
4
Sample output Copy
2 4 1 3 3 1 4 2
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int n,a[20],ans,cnt,b[800][20];
void dfs(int deep)
{
if(deep==n+1){
ans++;
for(int i=1;i<=n;i++) b[cnt][i]=a[i];
cnt++;
return;
}
for(int i=1;i<=n;i++){
bool flag=true;///判断当前位置是否合法
for(int j=1;j<deep;j++){
if(a[j]==i||(deep-j)==abs(i-a[j])){
flag=false;
break;
}
}
if(flag){//如果当先位置合法,则递归搜索下一个合法位置
a[deep]=i;
dfs(deep+1);
}
}
return;
}
int main()
{
while(scanf("%d",&n)!=EOF){
cnt=0;
ans=0;
dfs(1);
if(ans==0) printf("no solute!\n");
else{
for(int i=0;i<cnt;i++){
for(int j=1;j<=n;j++){
printf("%d ",b[i][j]);
}
printf("\n");
}
}
}
return 0;
}