poj1753 Flip Game 枚举+BFS

来源:互联网 发布:电视频道直播软件下载 编辑:程序博客网 时间:2024/05/29 13:23
#include<iostream>#include<queue>#include<cstdio>#include<cstring>using namespace std;struct st{ int cur;//当前格局 int choose;//已选了哪几个格子 int step;//步数}w,temp;const  int res=((1<<16)-1);int dirt[4][2]={0,1,0,-1,1,0,-1,0};bool flag[res+1];//判重int BFS(){ queue<st>q; q.push(w); int x,y; while(!q.empty()) {  w=q.front();  q.pop();  if(w.cur==0||w.cur==res)   return w.step;  for(int j=0;j<16;j++)  {   if(w.choose&(1<<j))//第j个格子已选过    continue;   temp.choose=w.choose|(1<<j);   if(flag[temp.choose])    continue;   flag[temp.choose]=true;   temp.step=w.step+1;   temp.cur=w.cur^(1<<j);   y=j%4;   x=(j-y)/4;   for(int k=0;k<4;k++)   {    int xx=x+dirt[k][0];    int yy=y+dirt[k][1];    if(xx<0||xx>=4||yy<0||yy>=4)     continue;    temp.cur^=(1<<(4*xx+yy));   }   q.push(temp);  } } return -1;}int main(){ char ch; int ans; while(cin>>ch) {  w.cur=w.step=w.choose=0;  if(ch=='w')   w.cur++;  memset(flag,false,sizeof(flag));  for(int i=1;i<16;i++)  {   cin>>ch;   if(ch=='w')    w.cur|=(1<<i);  }  ans=BFS();  if(ans>=0)   printf("%d\n",ans);  else   printf("Impossible\n"); } return 0;}


 

原创粉丝点击