N皇后問題
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 13998 Accepted Submission(s): 6376
你的任務是,對於給定的N,求出有多少種合法的放置方法。
代碼:
#include<stdio.h>
int tot=0,row,line[10],n;
int main()
{
void search(int );
int a[11];
for(n=1;n<=10;n++)//預處理
{
tot=0;
search(0);
a[n]=tot;
}
while(scanf("%d",&n)!=EOF&&n)
printf("%d\n",a[n]);
return 0;
}
void search(int row) //遞歸搜索可行解
{
int i,j;
if(row==n) tot++; //當row=n時,說明每一行的皇后都不衝突,即爲可行解
else
for(i=0;i<n;i++)
{
int ok=1;
line[row]=i; //嘗試把第row行的皇后放在i列上
for(j=0;j<row;j++) //檢驗是否與前面已放好的皇后衝突
{
if(line[row]==line[j]||line[row]-row==line[j]-j||line[row]+row==line[j]+j)
{
ok=0;
break; //,跳出最內層循環如果衝突,停止搜索,返回上一級遞歸回溯。回溯法高效的關鍵。
}
}
if(ok)
search(row+1);
}
}