解题思路: 没有写过n皇后问题的话直接看这个会不太理解。建议先弄清n皇后问题在看这个。在黑皇后搜索的状态下,加入对白皇后状态的搜索。和原本n皇后的区别在于,当对黑皇后搜索到满足状态时不是直接计数,而是转为对白皇后进行状态搜索。
#include<iostream>
#include<cmath>
using namespace std;
int map[10][10], n, ans = 0;
int bookblack[10], bookwhite[10];//用来标记第i行的皇后放在哪一列上
bool judgeblack(int x)//参数是行
{
for (int i = 1; i < x; i++)//第x行后面都还未被填充,不用遍历
//两种不符合的情况。1:x行此时对应的列放置了黑皇后。2:(x,bookblack[x])对角线上有黑皇后存在(用||后面的式子判断)
if (bookblack[x] == bookblack[i] || abs(x - i) == abs(bookblack[x] - bookblack[i]))
return false;
return true;
}
bool judgewhite(int x)
{
for (int i = 1; i < x; i++)//第x行后面都还未被填充,不用遍历
if (bookwhite[x] == bookwhite[i] || abs(x - i) == abs(bookwhite[x] - bookwhite[i]))
return false;//不符合情况同上面黑皇后的注释
return true;
}
void dfswhite(int x)
{
if (x == n + 1)//白皇后遍历完成,此时进行计数
{
ans++;
return;
}
for (int i = 1; i <= n; i++)
{
if (map[x][i] == 0 || bookblack[x] == i)
continue;
bookwhite[x] = i;
if (judgewhite(x))
dfswhite(x + 1);
}
}
void dfsblack(int x)
{
if (x == n + 1)//黑皇后遍历完成,遍历白皇后状态
dfswhite(1);
for (int i = 1; i <= n; i++)//在x行的基础上遍历列
{
if (map[x][i] == 0)
continue;
bookblack[x] = i;//先假定x行i列可放置,再在下面进行判断,不可以的话后面遍历会覆盖掉此时的值
if (judgeblack(x))
dfsblack(x + 1);
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> map[i][j];
dfsblack(1);//dfs遍历行
cout << ans << endl;
return 0;
}