HDU - 2553 N皇后问题 【DFS】

Description

在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 <cstring>
#include <cmath>

using namespace std;

int a[12];
int cnt;
int n;

// 判断是否可以放置
bool place(int t){
    for (int i = 1; i < t; i++)
        // 斜方向                       同一列
        if (abs(i-t)==abs(a[i]-a[t]) || a[i]==a[t])
            return false;
    return true;
}

void dfs(int t){
    if (t > n)
        cnt++;
    else
        for (int i = 1; i <= n; i++){
            a[t] = i; // 第t行放置在第i列
            if (place(t))
                dfs(t+1);
        }
}

int main()
{
    int ans[12];
    int x;
    // 先打表
    for (int i = 1; i <= 10; i++){
        memset(a, 0, sizeof(a));
        cnt = 0, n = i;
        dfs(1);
        ans[i] = cnt;
    }
    while (cin >> x && x!=0){
        cout << ans[x] << endl;
    }
    return 0;
}
发布了339 篇原创文章 · 获赞 351 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/Aibiabcheng/article/details/105353555