HDU 2553 N皇后问题 深搜
http://acm.hdu.edu.cn/showproblem.php?pid=2553
题意:
给出个N,代表N*N表格,在里面放N个皇后,要保证每个皇后之间不会攻击到,皇后的攻击范围:自己所在的那一行,自己所在的那一列,自己所在的两条
45度对角线。
坑爹:
如果输入一个N就去搜一次的话,数据给出每一次的N都是10的话就会超时。
解法:
反正这题N最大才10,就把1到10的结果先保存在数组中,然后每输入一次N就利用下表访问一次数组得到答案。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 using namespace std; 3 4 int N; 5 int count = 0; 6 int num[20]; 7 int A[20] = {0}; 8 9 void DFS(int mid) 10 { 11 if(mid == N ) 12 { 13 count++; 14 } 15 else 16 { 17 for(int i = 0 ; i < N ; i ++ ) 18 { 19 int flag = 1; 20 A[mid] = i; 21 for(int j = 0 ; j < mid ; j ++ ) 22 { 23 if(A[mid] == A[j] || mid - A[mid] == j - A[j] || mid + A[mid] == j + A[j] ) 24 { 25 flag = 0; 26 break; 27 } 28 } 29 if(flag) 30 { 31 DFS(mid + 1); 32 } 33 } 34 } 35 } 36 37 int main() 38 { 39 for(int i = 0 ; i < 10 ; i ++ ) 40 { 41 count = 0; 42 memset(A,0,sizeof(A)); 43 N = i + 1; 44 DFS(0); 45 num[i] = count; 46 } 47 while(cin>>N,N) 48 { 49 cout<<num[N - 1]<<endl; 50 } 51 52 return 0; 53 }