C - N Queens Problem DFS

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 total number of lines, each line a positive integer n ≤ 10, and represents the number of Queen board; if N = 0, indicating the end. Output total number of lines, each line a positive integer representing the number of different placement Queen corresponding input line. Sample Input

1
8
5
0

Sample Output

1 
92 
10 
N queens problem in DFS's title should be a more common way of thinking: there are N form Queen N rows and N columns so each Queen to occupy the i-th row so the Queen is the i-th row so we just record where the Queen As columns can be determined whether it on a diagonal line can be abs (mark [i] -mark [ x]) == abs (ix) determining whether the slope is equal to 1!;
#include<iostream>
#include<math.h>
#include<cstring>
using namespace std;
int n;
int mark[15];//保存皇后在的每一列 
int ans;
int arr[11];
int check(int x){
    for(int i=1;i<x;i++)
    {
        if(abs(mark[i]-mark[x])==abs(i-x)||mark[i]==mark[x])
            return 0;
    }
    return 1;
}
void dfs(int x){
    if(x>n){
        ans++;
        return ;
    }
    for(int i=1;i<=n;i++){
        mark[x]=i;
        if(check(x)){
            dfs(x+1);
        }
    }
}

int main()
{
    for(int i=1;i<=10;i++){
//        memset(mark,0,sizeof(mark));
        = ANS 0 ; 
        n- = I; 
        DFS ( . 1 ); 
        ARR [I] = ANS; 
    } // ,, or will play table TLE 
    the while (n-CIN >> && n-) { 
        COUT << ARR [n-] << endl; 
    } 
    return  0 ; 
}

 



Guess you like

Origin www.cnblogs.com/Accepting/p/11237597.html