jueshiyingcai 2013-03-17 04:34:00
点我顶贴
收藏
删除
测试结果错误.错误结果为:1 3 5 7 2 4 6
1 4 7 3 6 2 5
1 5 2 6 3 7 4
40
正确结果应为:1 3 5 7 2 4 6
1 4 7 3 6 2 5
1 5 2 6 3 7 4
40
代码如下
#include<iostream>
using namespace std;
int a[20],ans=0,n;
int TRY(int x,int y)
{
int j=1;//j为行指针
while(j<x)
{ if((a[j]==y)||(abs(x-j)==abs(a[j]-y)))
return 0;
j=j+1;
}
return 1;
}
void place(int x)
{
int y;
if(x>n)
{ans++;
if(ans<=3)
{for(int i=1;i<=n;i++)
{cout<<a[i]<<' ';}
cout<<endl;}
}
else
{
for(y=1;y<=n;y++)
if(TRY(x,y))
{a[x]=y;
place(x+1);
}
}
}
int main()
{
cin>>n;
if(n<=3)
cout<<0<<endl;
place(1);
cout<<ans<<endl;
//system("pause");
return 0;
}