N Queens (queen.cpp)
[Description Title]
N * N placed on board the Queen N (n <= 10) from each other against attacks (i.e. any line in the board, and any one can not place any two queens on a diagonal line), all programming solver display method.
[Input Format]
Input: n
[Output Format]
Each output line of a scheme, each program sequentially output column where the Queen, separated by a space there between the respective numbers. If there is no program, the output no solute!
[Sample input]
4
[Output Sample]
2 4 1 3
3 1 4 2
[solution]
DFS can directly see the problem. The main method is to DFS each line as a box, each box DFS only considers the current (ie the current row) Queen pendulum. When the n rows of each line to determine the position of the queen will find a a method Here are the most important snippet:
Determine whether the Queen before the attack, because each line is the box so no need to consider as a line of queens attack.
[Code (the AC)]
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
int queen[100];
int num; // whether 行
bool flag = false; // determines whether the solvability flag
void n_queen(int n){
if(n>num){
flag = true; // solvable, update flag
for (int i = 1; i <= num; ++ i) {// Output Solutions
printf("%d ",queen[i]);
}
printf("\n");
}
else {
for(int i=1;i<=num;++i){
bool k=true;
for(int j=1;j<n;++j){
if(n-j==i-queen[j]||i==queen[j]||n+i==queen[j]+j){//'\'斜||同一列||'/'斜
k=false;
break;
}
}
if(k){
queen[n]=i;//摆好这一行
n_queen(n+1);//准备放下一行
}
}
}
}
int main(){
freopen("queen.in","r",stdin);
freopen("queen.out","w",stdout);
memset(queen,false,sizeof(queen));
scanf("%d",&num);
n_queen(1);//从第一行放
if(flag==false)printf("no solute!");
return 0;
}