N皇后问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 11163 Accepted Submission(s): 4971
Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1 8 5 0
Sample Output
1 92 10#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <ctype.h> int ok,tot,n; int c[11]; void search(int cur) { int i,j; //必须局部变量 if(cur==n) tot++; else { for( i=0;i<n;i++) { ok=1; c[cur]=i; for( 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() { int k; int s[11]; for(k=1;k<=10;k++) { n=k; //注意n的值 tot=0; search(0); s[k]=tot; } while(scanf("%d",&n)!=EOF) { if(n==0) break; printf("%d\n",s[n]); } return 0; }