卧薪尝胆,厚积薄发。
皇后
Date: Fri Aug 24 17:14:22 CST 2018 In Category: NoCategory

Description:

$n$ 皇后问题,棋盘有些地方不能放。
$1\le n \le 16$

Solution:

搜索 $+$ 位运算。

Code:


#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
int n;
#define MAXN 17
int p[MAXN];
long long ans = 0;
void dfs(int pos,int l,int r,int u)
{
if(pos == n + 1)
{
++ans;
return;
}
int k = l | r | u | p[pos];
for(int i = 0;i < n;++i)
{
if((k & (1 << i)) == 0)
{
dfs(pos + 1,(l | (1 << i)) << 1,(r | (1 << i)) >> 1,u | (1 << i));
}
}
return;
}
int main()
{
scanf("%d",&n);
int k;
for(int i = 1;i <= n;++i)
{
for(int j = 1;j <= n;++j)
{
scanf("%d",&k);
p[i] |= (k << (j - 1));
}
}
dfs(1,0,0,0);
cout << ans << endl;
return 0;
}
In tag: 算法-搜索
Copyright © 2020 wjh15101051
ღゝ◡╹)ノ♡