在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1
8
5
0
Sample Output
1
92
10
Submit Status
描述
VJudge Status
By checking remote status page every 10 minutes.
OJ Status
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1
8
5
0
Sample Output
1
92
10
Submit Status
描述
VJudge Status
By checking remote status page every 10 minutes.
OJ Status
HDU
看来以后做题要学会习惯打表,就因为时间超限快坑死了,还是得长个记性。
先附上时间超限的代码,提经自己。
#include <iostream>
using namespace std;
int n,tot,ok;
int c[1001];
void search(int cur)
{
if(cur==n)
tot++;
else
for(int i=0;i<n;i++){
int ok=1;
c[cur]=i;
for(int j=0;j<cur;j++){
if(c[cur]==c[j]||cur-c[cur]==j-c[j]||cur+c[cur]==j+c[j])
{
ok=0;
break;
}
}
if(ok)
search(cur+1);
}
}
int main()
{
while(cin>>n&&n!=0)
{
tot=0;
search(0);
cout<<tot<<endl;
}
return 0;
}
下面是打表解决的
#include <iostream>
using namespace std;
int a[15],b[15],tot;
void search(int cur,int n)
{
if(cur==n)
tot++;
else
{
for(int i=0;i<n;i++)
{
a[cur]=i;
int ok=1;
for(int j=0;j<cur;j++)
{
if(a[cur]==a[j]||cur-a[cur]==j-a[j]||cur+a[cur]==j+a[j])
{
ok=0;
break;
}
}
if(ok)
search(cur+1,n);
}
}
}
int main()
{
for(int i=1;i<=10;i++)
{
tot=0;
search(0,i);
b[i]=tot;
}
int m;
while(cin>>m&&m)
{
cout<<b[m]<<endl;
}
return 0;
}