题目描述 Description
在n×n格的棋盘上放置彼此不受攻击的n个皇后。按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。n后问题等价于再n×n的棋盘上放置n个皇后,任何2个皇后不妨在同一行或同一列或同一斜线上。
输入描述 Input Description
给定棋盘的大小n (n ≤ 13)
输出描述 Output Description
输出整数表示有多少种放置方法。
样例输入 Sample Input
8
样例输出 Sample Output
92
数据范围及提示 Data Size & Hint
n<=13
(时限提高了,不用打表了)
代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int N = 20;
int mp[N], ans = 0, n;
int check(int x)
{
int i, j;
for(i = 1; i < x; i++)
{
if(mp[i] == mp[x] || abs(mp[x]-mp[i]) == abs(x-i))
//不在同一列 或 不在同一对角线
return 0;
}
return 1;
}
void dfs(int x)
{
if(x == n+1) ans++;
for(int i = 1; i <= n; i++)
{
mp[x] = i;
if(check(x)) dfs(x+1);
}
}
int main()
{
scanf("%d", &n);
dfs(1);
printf("%d\n", ans);
return 0;
}