[蓝桥杯2017初赛]青蛙跳杯子 BFS

题目描述

X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。
*WWWBBB
其中,W字母表示白色青蛙,B表示黑色青蛙,*表示空杯子。
X星的青蛙很有些癖好,它们只做3个动作之一
1. 跳到相邻的空杯子里。
2. 隔着1只其它的青蛙(随便什么颜色)跳到空杯子里。
3. 隔着2只其它的青蛙(随便什么颜色)跳到空杯子里。
对于上图的局面,只要1步,就可跳成该局面:WWW*BBB
本题的任务就是已知初始局面,询问至少需要几步,才能跳成另一个目标局面。

输入

输入存在多组测试数据,对于每组测试数据:
输入为2行,2个串,表示初始局面和目标局面。输入的串的长度不超过15

输出

对于每组测试数据:输出要求为一个整数,表示至少需要多少步的青蛙跳。

样例输入

*WWBB
WWBB*
WWW*BBB
BBB*WWW

样例输出

2
10

 

 

#include<iostream>
#include<string>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<map>
#include<stack>
#include<queue>
#define ll long long
using namespace  std;
string s1,s2;
int len;
int dir[6]={1,-1,2,-2,3,-3};
struct node 
{
    int x;
    string s;
    int cnt;
};
void bfs()
{
    node now;
    for(int i=0;i<len;i++)
    {
        if(s1[i]=='*')
        {
            now.x=i;
            now.s=s1;
            now.cnt=0;
            break;
        }
    }
    queue<node>p;
    map<string ,int>mp;
    p.push(now);
    mp[s1]=1;
    while(!p.empty())
    {
        now=p.front();
        p.pop();
        for(int i=0;i<6;i++)
        {
            int tx=now.x+dir[i];
            string ss=now.s;
            if(tx>=0&&tx<len)
            {
                char x=ss[now.x];//交换位置
                ss[now.x]=ss[tx];
                ss[tx]=x;

                node temp;
                temp.x=tx;
                temp.s=ss;
                temp.cnt=now.cnt+1;

                if(ss==s2)
                {
                    cout<<temp.cnt<<endl;
                    return ;
                }

                if(mp.count(ss)==0)
                {
                    p.push(temp);
                    mp[ss]=1;
                }

            }
        }
    }
}
int main()
{
    while(cin>>s1>>s2)
    {
        len=s1.length();
        bfs();
    }
}

 

posted @ 2020-02-22 17:28  知道了呀~  阅读(528)  评论(0编辑  收藏  举报