简单bfs题
原题:zjnu 1227
题意:
翻转游戏是在一个长方形4×4棋盘共16个双面方块的游戏。每一块的一个面是白色的,另一个是黑色的,每一块要么是黑色或白色的一面向上。每一次你可以选择16个方块中的任意一个方块,将该方块,以及它的上下左右,一共五个方块都翻转一次。如果它们都存在的话。
解析:
利用状压思想,用一个int代表16个棋子的状态,只需要bfs这个数以及相应的步数即可
代码:
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string>
#include<string.h>
#include<map>
#include<queue>
#include<bitset>
using namespace std;
int t;
map<int,int>M;
void dfs(int a,int st){
if(a==0||a==(1<<16)-1)return;
for(int i=1;i<=16;i++){
int b=a;
b^=(1<<(i-1));
if(i%4)b^=(1<<(i));
if(i%4!=1)b^=(1<<(i-2));
if(i<=12)b^=(1<<(i-1+4));
if(i>=5)b^=(1<<(i-1-4));
if(M[b]==0)M[b]=st+1,dfs(b,st+1);
else if(M[b]>st+1)M[b]=st+1,dfs(b,st+1);
}
}
struct node{
int a,st;
node(int a,int st):a(a),st(st){}
};
int main(){
cin>>t;
while(t--){
M.clear();queue<node>Q;
int a=0;
M[0]=1e9,M[(1<<16)-1]=1e9;
for(int i=1;i<=4;i++){
char tmp[5];scanf("%s",tmp);
for(int j=0;j<=3;j++){
int pos=(i-1)*4+j;
if(tmp[j]=='b')a|=(1<<pos);
}
}
M[a]=1;
//我们需要用等于0表示一种情况还未出现过,所以把所有的步数+1
Q.push(node(a,1));
int ans=1e9;
while(!Q.empty()){
node y=Q.front();Q.pop();int a=y.a,st=y.st;
if(a==0||a==(1<<16)-1){ans=st;break;}
for(int i=1;i<=16;i++){
int b=a;
b^=(1<<(i-1));
if(i%4)b^=(1<<(i));
if(i%4!=1)b^=(1<<(i-2));
if(i<=12)b^=(1<<(i-1+4));
if(i>=5)b^=(1<<(i-1-4));
if(M[b]==0)M[b]=st+1,Q.push(node(b,st+1));
else if(M[b]>st+1)M[b]=st+1,Q.push(node(b,st+1));
}
}
if(ans==1e9)printf("Impossible\n");
else printf("%d\n",ans-1);
}
}