HDOJ2553 N皇后问题

来源:互联网 发布:怎么样学数据库 编辑:程序博客网 时间:2024/06/03 15:10

在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。

Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。

Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。

Sample Input
1
8
5
0

Sample Output
1
92
10

#include<iostream>#include<math.h>#include<cstring>using namespace std;int vis[3][20] = {0};int total = 0;int n;void search(int col){    if(col == n){        total++ ;        return;    }   else{    for(int i = 0; i < n; i++){        if(!vis[0][i] && !vis[1][col + i] && !vis[2][col - i + n]){            vis[0][i] = vis[1][col + i] = vis[2][col - i + n] = 1;            search(col + 1);            vis[0][i] = vis[1][col + i] = vis[2][col - i + n] = 0;        }    }   }}int main(){    int a[11];    for (n = 1; n <= 10; n++)    {        total = 0;        search(0);        a[n] = total;    }    cin >> n;    while(n > 0){    cout << a[n] << endl;    cin >> n;    }    return 0;}
0 0
原创粉丝点击