The goal of Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure.
For a given chess board where kk queens are already placed, find the solution of the queens problem.
Input
In the first line, an integer kk is given. In the following kk lines, each square where a queen is already placed is given by two integers rr and cc. rr and cc respectively denotes the row number and the column number. The row/column numbers start with . Output
Print a ×× chess board by strings where a square with a queen is represented by 'Q' and an empty square is represented by '.'. Constraints
There is exactly one solution
Sample Input 3
Sample Output
......Q.
Q.......
..Q.....
.......Q
.....Q..
...Q....
.Q......
....Q...
题意:
给出n,代表给出n个确定的棋子数坐标,输出任意一组满足条件的八皇后即可。
不能直接根据斜率进行判断
不知道为什么???
int judge(int x)
{
for(int i=; i<x; i++) //判断之前和走过的行是否有重复
{
int dd1=abs(i-x);
int dd2=abs(a[i]-a[x]);
if(dd1==dd2)
{
return ;
}
}
return ;
//对角线出现过即k=-1或1
//即斜率的绝对值=1
//即两者的横纵坐标对应相减后绝对值相等
}
dfs不知道怎么解释,详细解释看代码上的注释吧。
AC代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<cmath>
using namespace std; int a[];//记录第几行第几列下了棋
int aa[];//标记行
char s[][];//存图,记录输出
int b[],c[],d[];//标记列、斜率>0的对角线、斜率<0的对角线
//对角线需要开的大一点
int flag; //int judge(int x)//传入行
//{
// for(int i=0; i<x; i++) //判断之前和走过的行是否有重复
// {
// int dd1=abs(i-x);
// int dd2=abs(a[i]-a[x]);
// if(dd1==dd2)
// return 1;
// }
// return 0;
// //对角线出现过即k=-1或1
// //即斜率的绝对值=1
// //即两者的横纵坐标对应相减后绝对值相等
//}
//不知道为什么对角线这样判断会WA void dfs(int x)//传入行
{
if(flag==)
return ;
if(x>)
{
flag=;//因为只需要输出一组结果
for(int i=; i<; i++)
printf("%s\n",s[i]);
return ;
} if(aa[x])//如果该行标记过
dfs(x+);//则往下一行进行搜索
else
{
//如果该行未被标记过,则在该行进行下棋
for(int j=; j<; j++) //决定下在哪一列
{
//a[x]=j;//下上去
//if(b[j]==0&&(judge(x)==0)) //如果该列没有标记且两条对角线没有标记过
if(b[j]==&&c[x+j]==&&d[x-j+]==)
{
c[x+j]=;
d[x-j+]=;
b[j]=;
s[x][j]='Q';
dfs(x+);
s[x][j]='.';
b[j]=;
c[x+j]=;
d[x-j+]=;
}
}
}
return ;
} int main()
{
std::ios::sync_with_stdio(false);
cin.tie();
cout.tie();
int t;
while(cin>>t)
{
memset(a,,sizeof(a));
memset(aa,,sizeof(aa));
memset(b,,sizeof(b));
memset(c,,sizeof(c));
memset(d,,sizeof(d));
flag=;
for(int i=; i<; i++)
{
for(int j=; j<; j++)
s[i][j]='.';
}
int x,y;
for(int i=; i<t; i++)
{
cin>>x>>y;
c[x+y]=;
d[x-y+]=;//标记对角线
aa[x]=;//标记行
a[x]=y;//该点确定下棋了
b[y]=;//标记列
s[x][y]='Q';//确定改点需要输出
}
dfs();
}
return ;
}