HDU-2553 N queen problem [DFS]

Description

N queens are placed on the N * N checkerboard so that they do not attack each other (that is, any two queens are not allowed to be in the same row and same column, nor are they allowed to be on a diagonal line that forms a 45 angle with the board border .
your task is, for a given N, how many legitimate method of obtaining placed there.
 

Input

There are several lines, each line with a positive integer N≤10, indicating the number of chessboards and queens; if N = 0, it means the end.

Output

There are a number of lines, each with a positive integer, representing the number of different placements of the queen corresponding to the input line.

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;
}

 

Published 339 original articles · praised 351 · 170,000 views

Guess you like

Origin blog.csdn.net/Aibiabcheng/article/details/105353555