翻转游戏

简单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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值