AcWing 843. n-皇后问题
原题链接
中等
作者:
Value
,
2020-05-11 20:42:21
,
所有人可见
,
阅读 491
#include <iostream>
#include <cmath>
using namespace std;
const int N = 10;
int n;
int queen[N];
bool place(int t, int loc){
for(int i = 0; i < t; i ++ ){
if(queen[i] == loc || abs(queen[i] - loc) == abs(i - t)){
return false;
}
}
return true;
}
void dfs(int t){
if(t == n){
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < n; j ++ ){
if(queen[i] == j) cout << "Q";
else cout << ".";
}
cout << endl;
}
cout << endl;
return ;
}
for(int i = 0; i < n; i ++ ){
if(place(t, i)){
queen[t] = i;
dfs(t+1);
}
}
}
int main(){
cin >> n;
dfs(0);
return 0;
}