Information Contest -1035-n queens problem

Title Description

[Title] Italy 

People play chess very clear: the queen can not eat another piece to the number of steps in the horizontal, vertical, diagonal. How eight queens on the chessboard (8 * 8 squares), so that they can not be eaten by anyone!

This is the famous eight queens problem. 

[Input Format] 

An integer n (1 <= n <= 10) 

[Output format] 

Each output line corresponds to a scheme, all output lexicographical ordering scheme. Each column Queen sequentially outputs the program is located, adjacent two numbers separated by spaces. 

[Sample input] 

[Sample output] 

2 4 1 3

3 1 4 2


Code:

#include<cstdio>

#include<cstring>

// left oblique from [1,1] diagonally right from the [n, 1]

using namespace std;

int n,r,a[110];

bool col[110],row[110],lft[230],rht[230];

void dfs(int k){

if(k==n+1){

for(int i=1;i<=n;i++) printf("%d ",a[i]);

printf("\n");

}else{

for(int j=1;j<=n;j++){

if(row[k]&&col[j]&&lft[k+j-1]&&rht[j-k+n]){

a[k]=j;

row[k]=0;col[j]=0;lft[k+j-1]=0;rht[j-k+n]=0;

dfs(k+1);

a[k]=0;

row[k]=1;col[j]=1;lft[k+j-1]=1;rht[j-k+n]=1;

}

}

}

}

int main () {

scanf("%d",&n);

memset (col, 1, sizeof (col)); // fill a per line, the default is true, can be filled

memset (row, 1, sizeof (row)); // each column can only fill a

memset (lft, 1, sizeof (lft)); // each column can only fill a left oblique

memset (rht, 1, sizeof (rht)); // for each column can fill a right diagonal,

dfs(1);

return 0;

}

14915948-74f0efa19fa23b86.png
Left oblique and right oblique is calculated by the Four Queens, for example

Reproduced in: https: //www.jianshu.com/p/9da82e0104d0

Guess you like

Origin blog.csdn.net/weixin_33739627/article/details/91070315