Test instructions
The squares of the N*n (n <= 10) have placed n queens so that they do not attack each other (that is, any 2 queens are not allowed to be in the same row, in the same column, or in a diagonal line that is 45-angled to the checkerboard border. Your task is to find out how many legal placement methods are available for a given n.
Ideas:
Backtracking + pruning, a bit similar to DFS full arrangement. Use Emp[i] to represent the row from left to right for the first queen, so that all queens are not in the same column by default.
Code:
#include <cstdio>#include<iostream>#include<cstring>#include<cstring>#include<cmath>#include<cstdlib>#include<algorithm>using namespacestd;Const intMAXN = at;intEMP[MAXN];//Emp[i] represents the row from left to right the first queenintUSED[MAXN];//Mark this line is already in useintN;intCnt//the total number of reasonable solutionsintCheckintKey//determine if the position of the first Queen is reasonable{ if(used[Emp[key])//Determine whether the row is reasonable return 0; for(inti =1; I < key; i++)//judging whether oblique and reasonable if(ABS (i-key) = = ABS (Emp[i]-Emp[key])) return 0; return 1;}voidBacktrackintkey) { if(Key > N)//a solution satisfying the conditioncnt++; Else { for(inti =1; I <= N; i++)//The Queen of the key column can have N options (states) placed on the 1-n line{Emp[key]= i;//Put the first key queen on line I if(check (key))//legitimacy{Used[i]=1;//Mark this line is already in useBacktrack (key +1);//continue to solve the next queen .Used[i] =0;//Recovery Site } } }}intMain () {//freopen ("OUT.txt","W", stdout); while(Cin >>N) {cnt=0; memset (EMP,0,sizeof(EMP)); memset (Used,0,sizeof(used)); Backtrack (1);//start with the first Queen . } return 0;}
HDU 2553 N Queen problem (backtracking)