Basic exercises 2n Queens blue bridge BASIC-27 (search)

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

  A first act input 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
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <deque>
#include <cmath>
#include <map>

using namespace std;
typedef long long ll;

#define INF 0x7fffffff
const double inf=1e20;
const int maxn=1000+10;
const int mod=1e7;
const double pi=acos(-1);

int a[10][10];
int vis[3][50];
int vis2[3][50];
int tot;
int n;
int c[50];

void search_2(int cur){
    if(cur==n){
        tot++;
    }
    else for(int i=0;i<n;i++){
        if(!vis2[0][i]&&!vis2[1][cur+i]&&!vis2[2][cur-i+n]&&a[cur][i]==1){
            vis2[0][i]=vis2[1][cur+i]=vis2[2][cur-i+n]=1;
            a[cur][i]=0;
            search_2(cur+1);
            a[cur][i]=1;
            vis2[0][i]=vis2[1][cur+i]=vis2[2][cur-i+n]=0;
        }
    }
}

void search_(int cur){
    if(cur==n){
        search_2(0);
    }
    else for(int i=0;i<n;i++){
        if(!vis[0][i]&&!vis[1][cur+i]&&!vis[2][cur-i+n]&&a[cur][i]==1){
            vis[0][i]=vis[1][cur+i]=vis[2][cur-i+n]=1;
            a[cur][i]=0;
            search_(cur+1);
            a[cur][i]=1;
            vis[0][i]=vis[1][cur+i]=vis[2][cur-i+n]=0;
        }
    }
}

int main(){
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            scanf("%d",&a[i][j]);
        }
    }
    tot=0;
    search_(0);
    printf("%d\n",tot);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/wz-archer/p/12502376.html