http://acm.hdu.edu.cn/showproblem.php?pid=2553
I represents rows, Map[i] represents columns, and then uses DFS traversal backtracking
You can refer to this article:
http://blog.csdn.net/cambridgeacm/article/details/7703739
1#include <iostream>2#include <string>3#include <cstring>4#include <cstdlib>5#include <cstdio>6#include <cmath>7#include <algorithm>8#include <stack>9 using namespacestd;Ten One #defineMEM (A, B) memset (A,b,sizeof (a)) A - BOOLused[ the]; - //i means row, Map[i] represents the column the intmap[ the]; - intsol[ the]; - - intAns,n; + - + voidDfsintk) A { at inti,j; - - //Judging the end - if(k==n+1) - { -ans++; in return; - } to + for(i =1; i<=n;i++) - { the if(!Used[i]) * { $MAP[K] =i;Panax Notoginseng BOOLFlag =true; - the //Whether it's on a diagonal line + for(j=1; j<=k-1; j + +) A { the if((map[k]-map[j]) = = (K-j) | | (Map[k]-map[j]) = = (J-k)) + { -Flag =false; $ Break; $ } - } - if(flag) the { -Used[i] =true;WuyiDFS (k +1); the //not found, release used - //Backtracking WuUsed[i] =false; - } About } $ } - } - - A intMain () + { the intt,i; - //save is because there may be duplicate data in the background, the efficiency is the same for a single time $ for(i =1; i<=Ten; i++) the { theMEM (Used,false); theMEM (Map,0); then =i; -Ans =0; inDfs1); theSol[i] =ans; the } About the while(~SCANF ("%d", &n) &&N) the { theprintf"%d\n", Sol[n]); + } - return 0; the}
HDU 2553 (n Queen) (DFS)