Blue Bridge Cup 2n Queens deep search

It will be the default n queens problem

Basic exercises 2n Queens  
Time limit: 1.0s memory limit: 512.0MB
   
Problem Description
  Given an n * n board, the board can not be put in the position of some of the Queen. To now black board placed n and n-queens White Queen, so that any two black queens are not on the same line, same column or the same diagonal line, any two White Queen not in the same row, the same column or the same diagonal. Q. A total of how many put the law? n is 8 or less.
Input format
  input acts a first integer n, the size of the board.
  Subsequently n rows, each row of n an integer of 0 or 1, if a is an integer of 1, indicating the position corresponding to queen can be placed, if a is an integer of 0, indicating the position corresponding to the discharge can not be queen.
Output format
  output an integer representing the total number of species put law.
Sample input
. 4
. 1. 1. 1. 1
. 1. 1. 1. 1
. 1. 1. 1. 1
. 1. 1. 1. 1
sample output
2
Sample input
. 4
. 1 0. 1. 1
. 1. 1. 1. 1
. 1. 1. 1. 1
. 1. 1. 1. 1
Sample Output
0

Idea: to extend into 2N N Queens Queens, one-dimensional to two-dimensional cycle becomes.

#include<iostream>
using namespace std;
const int N = 10;
int a[N][N];
int n;
int ans;
bool colb[N],dlb[N],udlb[N],colh[N],dlh[N],udlh[N];
void dfs(int u)
{
    if(u==n){
        ans++;
        return ;
    }
    for(int i=0;i<n;++i){
        for(int j=0;j<n;++j){
            if(i!=j){
                if(!colb[i]&&!dlb[i+u]&&!udlb[n-i+u]&&!colh[j]&&!dlh[j+u]&&!udlh[n-j+u]&&a[u][i]==1&&a[u][j]==1){
                    colb[i]=dlb[i+u]=udlb[n-i+u]=colh[j]=dlh[j+u]=udlh[n-j+u]=true;
                    dfs(u+1);
                    colb[i]=dlb[i+u]=udlb[n-i+u]=colh[j]=dlh[j+u]=udlh[n-j+u]=false;
                }
            }
        }
    }
}
int main()
{
    cin>>n;
    for(int i=0;i<n;++i){
        for(int j=0;j<n;++j){
            cin>>a[i][j];
        }
    }
    dfs(0);
    cout<<ans<<endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/clear-love/p/11290497.html