#include<iostream>
using namespace std;
int n;
int pos[10];
//pos[3]=4 第三行的放在第四列
bool check(int x,int k){
//第x行能否放到第k列
//前面的x-1行依次检查:第a行 放在pos[a]列
for(int i=1; i<=x-1; i++){
//对角线 或者放在了同一列(已经保证不在同一行)
if(abs(k-pos[i])==abs(x-i)||pos[i]==k)
return false;
}
return true;
}
void dfs(int x){
if(x==n+1){
for(int i=1; i<=n; i++){ //行
for(int j=1; j<=n; j++){ //列
if(pos[i]==j) cout << "Q";
else cout << ".";
}
cout << endl;
}
cout << endl;
}
for(int i=1; i<=n; i++){
if(check(x,i)){
pos[x]=i;
dfs(x+1);
}
}
}
int main(){
cin >> n;
dfs(1);
return 0;
}
DFS—n皇后
猜你喜欢
转载自blog.csdn.net/jhckii/article/details/104128954
今日推荐
周排行