POJ 1753 Flip Game

本文介绍了一个使用位操作和广度优先搜索算法解决特定迷宫问题的方法。通过定义一系列位操作来改变迷宫状态,实现从初始状态到目标状态的转换,并计算最少的操作次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<cstdio>
#include <string>
#define ll long long
using namespace std;

int st,vis[(1 << 17)];

int change(int x,int w)
{
    x ^= (1 << w);
    if(w > 3)
    {
        x ^= (1 << (w - 4));
    }
    if(w < 12)
    {
        x ^= (1 << (w + 4));
    }
    if(w % 4)
    {
        x ^= (1 << (w - 1));
    }
    if(w % 4 < 3)
    {
        x ^= (1 << (w + 1));
    }
    return x;
}

int bfs()
{
    queue<pair<int,int> >q;
    pair<int,int>stt;
    stt.first = st,stt.second = 0;
    //cout << st << endl;
    q.push(stt);
    vis[st] = 1;
    if(st == 0 || st == 65535)
        return 0;
    while(!q.empty())
    {
        pair<int,int> te = q.front();
        q.pop();
        for(int i = 0;i < 16;i++)
        {
            int now = change(te.first,i);
            if(now == 0 || now == 65535)
                return te.second + 1;
            if(vis[now])
                continue;
            vis[now] = 1;
            q.push(make_pair(now,te.second + 1));
        }
    }
    return -1;
}

int main(){
		string gg;
		while(cin >> gg)
		{

        memset(vis,0,sizeof(vis));
        st = 0;
		 for(int j = 0;j < 4;j++)
            {
                if(gg[j] == 'b')
                {
                    st |= (1 << (j));
                }
            }
        for(int i = 1;i < 4;i++)
        {
            char s[11];
            scanf("%s",s);
            for(int j = 0;j < 4;j++)
            {
                if(s[j] == 'b')
                {
                    st |= (1 << (i * 4 + j));
                }
            }
        }
        //cout << st << endl;
        int ou = bfs();
        if(ou == -1)
            cout << "Impossible\n";
        else
            cout << ou << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值