东华oj进阶51 青蛙跳杯子

问题描述:

X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。

*WWWBBB

其中,W字母表示白色青蛙,B表示黑色青蛙,*表示空杯子。

X星的青蛙很有些癖好,它们只做3个动作之一:
  1. 跳到相邻的空杯子里。
  2. 隔着1只其它的青蛙(随便什么颜色)跳到空杯子里。
  3. 隔着2只其它的青蛙(随便什么颜色)跳到空杯子里。

对于上图的局面,只要1步,就可跳成下图局面:

WWW*BBB

本题的任务就是已知初始局面,询问至少需要几步,才能跳成另一个目标局面。

输入说明 :

输入为2行,2个串,表示初始局面和目标局面。

输入的串的长度不超过15

输出说明 :

输出要求为一个整数,表示至少需要多少步的青蛙跳。

输入范例 :

WWWBBB
BBB
WWW

输出范例 :

10

思路:

使用广搜,对于每一种情况判断出其变化范围,然后在这个范围内依次让对应青蛙和空白位置交换并入队,
同时记得去重--即建立一个map用来判断某种情况的出现次数,只有没出现时,这种情况才可以加入map

代码实现:

#include<bits/stdc++.h>
using namespace std;

string start,dest;
queue<string> q;
map<string,int> maps;
int res=0;

void BFS()
{
    while(q.size()!=0 && res==0)
    {
        string str1=q.front();
        int len=str1.size();
        q.pop();

        int spaceIndex=0;

        for(int i=0;i<len;i++)
        {
            if(str1[i]=='*')
                spaceIndex=i;
        }

        int beginIndex,endIndex;

        if(spaceIndex-3>=0)
        {
            beginIndex=spaceIndex-3;
        }
        else if(spaceIndex-2>=0)
        {
            beginIndex=spaceIndex-2;
        }
        else if(spaceIndex-1>=0)
        {
            beginIndex=spaceIndex-1;
        }
        else
        {
            beginIndex=spaceIndex;
        }

        if(spaceIndex+3<=len-1)
        {
            endIndex=spaceIndex+3;
        }
        else if(spaceIndex+2<=len-1)
        {
            endIndex=spaceIndex+2;
        }
        else if(spaceIndex+1<=len-1)
        {
            endIndex=spaceIndex+1;
        }
        else
        {
            endIndex=spaceIndex;
        }

        for(int i=beginIndex;i<=endIndex;i++)
        {
            if(i==spaceIndex) continue;
            string str2(str1);
            swap(str2[i],str2[spaceIndex]);

            if(str2==dest)
            {
                res=maps[str1]+1;
                break;
            }

            if(maps[str2]==0)
            {
                //cout<<str2<<" "<<str1<<" "<<maps[str1]<<endl;
                q.push(str2);
                maps[str2]=maps[str1]+1;
            }
        }
    }
}

int main()
{
    getline(cin,start);
    getline(cin,dest);

    q.push(start);
    maps[start]=0;

    BFS();

    cout<<res<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值