题目链接:https://cn.vjudge.net/problem/HDU-2553
题目描述
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1 8 5 0Sample Output
1 92 10
思路:
递归,n个皇后必然在n行,不放令第i个皇后在第i行,然后枚举第i行的每一列,满足要求就把第i个皇后放在这个位置 。需要打表,直接提交会超时。
AC代码:
#include <iostream>
#include <cmath>
using namespace std;
int col[12];
int n,ans;
bool Judge(int x,int y)
{
for(int i=1;i<x;i++) {
if(col[i] == y)
return false;
if(abs(i-x) == abs(col[i]-y))
return false;
}
return true;
}
void NNiang(int ord,int total)
{
if(ord == total+1) {
ans++;
return;
}
for(int i=1;i<=total;i++)
if(Judge(ord,i)) {
col[ord] = i;
NNiang(ord+1,total);
}
}
int main()
{
int ANS[12];
for(int i=1;i<=10;i++) {
ans = 0;
NNiang(1,i);
ANS[i] = ans;
}
while(cin >> n && n) {
cout << ANS[n] << endl;
}
}