# HDU 2553 N皇后问题

### N皇后问题

Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23201
Accepted Submission(s): 10344

### Sample Input

1
8
5
0

### Sample Output

1
92
10

### Source

2008 HZNU Programming Contest

### Analyze

• DFS 模板
• 位运算没有看懂，学的多了自然会懂，何必一直纠结。。。

### Code1: DFS

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <fstream>
#include <map>
#include <vector>
#include <cmath>
#include <limits.h>
using namespace std;

int ans[15], x[15];
int sum , n;

void DFS(int cur)
{
if(cur > n)
{
sum++;
return ;
}
else
{
for(int i=1; i<=n; i++)
{
x[cur] = i;
bool flag = true;

for(int j=1; j<cur; j++)
{
if(x[j] == x[cur] || abs(x[cur] - x[j]) == abs(cur - j))   //判断是否在同一列
{
flag = false;
break;
}
}
if(flag)
DFS(cur+1);
}
}
}
int main()
{
memset(ans, 0, sizeof(ans));

while(cin >> n && n)
{
if(ans[n] == 0)
{
sum = 0;
DFS(1);
ans[n] = sum;
}
cout << ans[n] << endl;
}

return 0;
}

### Code2： 位运算

#include<cstdio>
#include<cstring>

using namespace std;
int N,High,ans;

void DFS(int row,int ld,int rd)
{
if(row == High){ ans++; return;}

int Pos = ((~(row | ld | rd)) & High);
while(Pos)
{
int P = Pos & (-Pos);
Pos = Pos - P;
DFS(row+P, (ld+P)<<1, (rd+P)>>1);
}
}

int main()
{
while(~scanf("%d",&N) && N)
{
High = (1<<N)-1; ans = 0;
DFS(0,0,0);
printf("%d\n",ans);
}
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120