八皇后,经典递归问题
ti
#include<bits/stdc++.h>
using namespace std;
const int N = 95;
int n;
int res;
int ans[N][9];
int col[10], dg[N], edg[N];
int pos[10];
void print(){
for(int i = 1; i <= 8; i ++ ){
ans[res][i] = pos[i];
}
}
void dfs(int y){ //行
if(y > 8){
res ++ ;
print();
return ;
}
for(int i = 1; i <= 8; i ++ ){ //列
if(col[i] || dg[y - i + 8] || edg[y + i]) continue;
pos[y] = i;
col[i] = 1;
dg[y - i + 8] = 1;
edg[y + i] = 1;
dfs(y + 1);
col[i] = 0;
dg[y - i + 8] = 0;
edg[y + i] = 0;
}
return ;
}
int main()
{
dfs(1);
while(cin>>n){
for(int i = 1; i <= 8; i ++ ){
cout<<ans[n][i];
}
cout<<endl;
}
return 0;
}