N皇后问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 6921 Accepted Submission(s): 3134
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解题分析dfs,或者bfs解题代码#include <iostream> #include <stdio.h> #include <cstring> using namespace std; int n,t,flag,line[15]; int count[15]; void dfs(int row) { if(row==n) t++; else for(int i=0; i<n; i++) { line[row]=i; flag=1; for(int j=0; j<row; j++)//判断在第row行第i列是不是和已经放置好的冲突 if(line[row]==line[j] || line[row]-row==line[j]-j || line[row]+row==line[j]+j) { flag=0; break; } if(flag) dfs(row+1); } } int main() { int a; for(n=1; n<=10; n++) { t=0; dfs(0);//每次都是从第0行开始 count[n]=t; } while(scanf("%d",&a)!=EOF && a)//注意这样的输入方法,省时间 printf("%d\n",count[a]); return 0; }