#HDU 2553 N Queens problem (dfs)

Problem Description

In the checkerboard-N * N N queens placed such that they do not attack each other (i.e., does not allow any two queens in the same row, same column, is not allowed in the board frame 45 on a diagonal angle .
your task is, for a given N, how many legitimate method of obtaining placed there.
 

 

 

Input

There are several lines of a positive integer n ≤ 10, and represents the number of Queen board; if N = 0, indicating the end.

 

 

Output

There are a number of lines, each a positive integer representing the number of different placement Queen corresponding input line.

 

 

Sample Input

 

1 8 5 0

 

 

Sample Output

 

1 92 10

 This question is still the first to write that winter will just learning dfs, look for a long look at problem solution was to write, write now more relaxed, and the method was not the same, this time with the one-dimensional

Ideas: First, a total of N rows and N columns, N queens, we need only consider the column and the slope of these two factors, because if this line has a direct search conditions are met, then the next line, the line is not as judgment conditions, so we use int array vis, both expressed in this column is put Queens, he said he placed the first of several columns. For example, we determined the time to row 3, column 2, we have from the first row to the second row traversal, to see if there vis = 2 [1] or [2] vis = 2, then determining the absolute value of the slope it is 1 can be friends.

Know ye not that the T, I directly hit the gas meter. .

AC Code: 

#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 10;

int n, sum, vis[maxn];
bool check (int d, int t) {
    for (int i = 1; i < d; i++) {
        if (vis[i] == t || abs(vis[i] - t) == abs(i - d))
            return false;
    }
    return true;
}
void dfs(int d) {
    if (d == n + 1) {
        sum++;
        return ;
    }
    for (int i = 1; i <= n; i++) {
        if (check (d, i)) {
            vis[d] = i;
            dfs (d + 1);
            vis[d] = 0;
        }
    }
}

int main()
{
    p[1] = 1;
    p[2] = 0;
    p[3] = 0;
    p[4] = 2;
    p[5] = 10;
    p[6] = 4;
    p[7] = 40;
    p[8] = 92;
    p[9] = 352;
    p[10] = 724;
    while (cin >> n && n) {
        cout << p[n] << endl;
    }
    return 0;
}

 

 

Guess you like

Origin blog.csdn.net/weixin_43851525/article/details/92197515