首页 > 代码库 > [ An Ac a Day ^_^ ] hdu 2553 N皇后问题 搜索

[ An Ac a Day ^_^ ] hdu 2553 N皇后问题 搜索

曾经想过一天一AC 坚持下来的确不容易额 (我是没坚持下来 尽量以后坚持……

经典的N皇后问题 搜索的入门问题 学了这么久竟然一直没敲过 今天敲一下……

这道题也不是很简单额 纯暴力就超时了 要打一下表……

而且有一个小的优化

每次判断是否合理不用铺满图再判断

只需要判断当前放皇后的位置的上方 左上和右上有没有皇后就可以了

自己想也不好想-_-||

 1 #include<stdio.h> 2 #include<iostream> 3 #include<algorithm> 4 #include<math.h> 5 #include<string.h> 6 #include<string> 7 #include<map> 8 #include<set> 9 #include<vector>10 #include<queue>11 #include<list>12 #define M(a,b) memset(a,b,sizeof(a))13 using namespace std;14 typedef long long ll;15 const int inf=0x3f3f3f3f;16 const int maxn=1e1+10;17 int dx[8]= {0,0,1,-1,1,-1,1,-1};18 int dy[8]= {1,-1,0,0,-1,1,1,-1};19 //---------------------------------------ヽ(^。^)丿20 int cnt,n,ans[maxn];21 int _map[maxn];22 void dfs(int x)23 {24     if(x>n)25     {//只要能搜到这一步一定符合条件了26         cnt++;27         return ;28     }29     for(int i=1; i<=n; i++)30     {31         _map[x]=i; //放置皇后32         bool ok=true;33         for(int j=x-1;j>=1;j--)34             if(_map[j]==i|| //正上方35                _map[j]==i-x+j|| //左上方36                _map[j]==i+x-j) //右上方37                     ok=false;38         if(ok) dfs(x+1); //符合条件继续搜索39     }40     return ;41 }42 int main()43 {44     M(ans,-1);45     while(~scanf("%d",&n)&&n)46     {47         if(ans[n]!=-1)48             printf("%d\n",ans[n]);49         else50         {51             M(_map,-1);52             cnt=0;53             dfs(1);54             ans[n]=cnt; //打表55             printf("%d\n",cnt);56         }57     }58     return 0;59 }60 /*61 62 163 864 565 066 67 */

 

[ An Ac a Day ^_^ ] hdu 2553 N皇后问题 搜索