poj1753 Flip Game 枚举+BFS

#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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值