2n Queen's question

Keywords: less

Problem description
Given an n*n chessboard, there are some positions in the chessboard where the queen cannot be placed. Now we need to put n black queens and n white queens into the chessboard, so that any two black queens are not on the same line, column or diagonal, and any two white queens are not on the same line, column or diagonal. How many ways are there in total? N is less than or equal to 8.
Input format
The first line of input is an integer n, representing the size of the chessboard.
Next N lines, each line has n integers of 0 or 1. If an integer is 1, it means that the corresponding position can be put to the queen. If an integer is 0, it means that the corresponding position cannot be put to the queen.
Output format
Output an integer indicating the total number of playback methods.
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

This is a promotion problem of the eight queens. Go straight to the code

#include<iostream>
using namespace std;
int dp[10][10]= {0},c[10]= {0},h[10]= {0},n,count=0;
int judgement(int x,int y,int *b,int *l) { //Judge whether the queen can be put here
    if(dp[x][y]==0||(y==l[x])) return 0;
    for(int i=1; i<=x; i++) {
    if((i-b[i])==(x-y)) return 0;
    if(b[i]==y) return 0;
    if((i+b[i])==(x+y)) return 0;
    }
    return 1;
}
void Placeh(int index) {

    for(int i=1; i<=n; i++) {
        if(judgement(index,i,h,c)) {
            h[index]=i;
            if(index==n) {
                count++;
                h[index]=0;
                return;
            }
            Placeh(index+1);
            h[index]=0;
        }
    }
}
void Place(int index) {

    for(int i=1; i<=n; i++) {
//      cout<<judgement(index,i,c,h)<<endl;
        if(judgement(index,i,c,h)) {
            c[index]=i;
            if(index==n) {
                Placeh(1);
                c[index]=0;
                return;
            }
            Place(index+1);
            c[index]=0;
        }
    }
}
int main() {
    cin>>n;
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=n; j++)
            cin>>dp[i][j];
    }
    Place(1);
    cout<<count<<endl;
    return 0;
}

Posted by therealchuckles on Sun, 03 May 2020 21:58:16 -0700