N皇后问题
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 <bits/stdc++.h> using namespace std; int n,tot=0; int col[12]={0}; bool check(int c,int r ){ //当前坐标 (r,c) for(int i=0;i<r;i++){ if(col[i]==c || abs( col[i]-c)== abs(i-r) ) return false; } return true; } void dfs(int r){ if(r==n) { tot++; return ; } for(int c=0;c<n;c++){ if( check(c,r)){ col[r]=c; dfs(r+1); } } } int main(){ int ans[12]={0}; for(n=0;n<=10;n++){ tot=0; memset(col,0,sizeof(col) ); dfs(0); ans[n]=tot; } while(~scanf("%d",&n)&&n){ cout<<ans[n]<<endl; } return 0; }