DFS + 打表

代码入下:

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
//  棋盘       答案
int chess[12], s[12];
int ans, n;
void dfs(int k)//设置第k行,即前k-1行已经设置好了
{
    if(k == n){//到头了,说明此路走得通,计数器+1
        ++ans;
        return;
    }
    for (int i = 0; i < n;i++){
        int j;
        for (j = 0; j < k;j++){
            if(i == chess[j]||(k-j) == abs(i-chess[j]))//不能吃到
                break;
            }
        if(j == k) {//满足条件,则设置下一行
            chess[k] = i;
            dfs(k + 1);
        }
    }
}
int main()
{
    //打表
    for (int i = 1; i <= 10;++i){
        //初始化
        ans = 0;
        n = i;
        memset(chess, 0, 12);
        dfs(0);
        s[i] = ans;
    }
        while (cin >> n)
        {
            if (!n)
                break;
            cout << s[n] << endl;//取数
        }
    return 0;
}