因为题目给定了两个皇后的位置,相当于一个限制条件。
在dfs进行搜索的时候,先不用判断是否在这行的皇后在这个位置上。把所有的情况都搜索出来,然后在输出的时候进行判断即可,最坏情况下就相当于求八皇后问题的所有解。
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<list>
#include<queue>
#define mm(a,b) memset(a,b,sizeof(a))
#define ACCELERATE (ios::sync_with_stdio(false),cin.tie(0))
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define MAXN 0x3f3f3f3f3f3f3f3f
#define PI acos(-1.0)
#define E exp(1.0)
using namespace std;
//#define debug
const int N=8;
#define FREE -1
#define NOT_FREE 1
int row[N],col[N],dpos[2*N-1],dneg[2*N-1];
bool e[N][N];
void inin(){
for(int i=0;i<=N;i++){
row[i]=col[i]=FREE;
}
for(int i=0;i<2*N-1;i++){
dpos[i]=dneg[i]=FREE;
}
}
void printboard(){
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(e[i][j]){
if(row[i]!=j) return;
}
}
}
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
cout<<(row[i]==j?"Q":".");
}cout<<endl;
}
}
void dfs(int i){
if(i==N){
printboard();
return;
}
for(int j=0;j<N;j++){
if(col[j]!=FREE||dpos[i+j]!=FREE||dneg[i-j+N-1]!=FREE){
continue;
}
row[i]=j;col[j]=NOT_FREE;dpos[i+j]=NOT_FREE;dneg[i-j+N-1]=NOT_FREE;
dfs(i+1);
row[i]=col[j]=dpos[i+j]=dneg[i-j+N-1]=FREE;
}
}
int main()
{
#ifdef debug
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif // debug
ACCELERATE;
inin();
mm(e,0);
int k;
cin>>k;
while(k--){
int a,b;
cin>>a>>b;
e[a][b]=1;
}
dfs(0);
return 0;
}