日常刷水题
棋盘上的DFS。一开始忘了(彻底),看了看小白,恍然大(雾)悟。
从每次按行搜索,搜索当前行的每一列是否能放皇后,于是只需要记录列与对角线是否被“皇后所占”,若没有则放上,若已占则继续搜索,若放上,之后别忘记回溯到上一步状态,我们可以建一个二维bool数组来记录当前你所想要放皇后的位置是否已有其他皇后,是否已经被其他皇后所覆盖(我们不需要记录每个格子是否被覆盖,因为一个皇后一旦被放置,则其所在列便不可放&&其所在对角线也不可放,只需要知道我们当前位置的列数然后加上当前的是第几个被放置的即可(离散化?))
a[0][i]表示当前i列上是否已有皇后,a[1][tot+i]和a[2][tot-i+n]表示当前对角线上是否已有皇后
代码如下:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int tot;
bool pd[2][50];
void dfs(int x)
{
//cout<<"wtf of n: "<<n<<endl;
//cout<<"wtf of x: "<<x<<endl;
if(x == n)
{
//cout<<"tot1:"<<tot<<endl;
tot++;
//cout<<"tot2:"<<tot<<endl;
}
else
{
for(int i = 0;i < n;i++)
{
//cout<<"wtf of i: "<<i<<endl;
if(!pd[0][i] && !pd[1][x+i] && !pd[2][x-i+n])
{
pd[0][i] = pd[1][x+i] = pd[2][x-i+n] = 1;
//cout<<"haha: "<<pd[0][i]<<pd[1][x+i]<<pd[2][x-i+n]<<endl;
dfs(x+1);
pd[0][i] = pd[1][x+i] = pd[2][x-i+n] = 0;
//cout<<"woc: "<<pd[0][i]<<pd[1][x+i]<<pd[2][x-i+n]<<endl;
}
}
}
}
int main()
{
memset(pd,0,sizeof(pd));
scanf("%d",&n);
//cout<<"n:"<<n<<endl;
dfs(0);
printf("%d",tot);
return 0;
}
//沉溺OSU不能自拔ing
THE END
By Peacefuldoge