蓝桥杯 青蛙跳杯子(广搜)

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


  *WWWBBB


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


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


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


  WWW*BBB


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


  输入为2行,2个串,表示初始局面和目标局面。
  输出要求为一个整数,表示至少需要多少步的青蛙跳。
样例输入
*WWBB
WWBB*
样例输出
2

思路:很明显的广搜嘛,我居然还想着是深搜不断记录到达某个状态的最小步数,ε=(´ο`*)))唉.

广搜正解,每种状态只可入队一次,每个串的每只青蛙都有6种跳跃方式,用map记录状态.

代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<vector>
#include<cmath> 
#include<map>
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
const double esp = 1e-7;
const int ff = 0x3f3f3f3f;
map<int,int>::iterator it;

struct node
{
	string s;
	int step;
	node(string s,int step):s(s),step(step){}
};

string s1,s2;
int ans;
map<string,int> mp;

void bfs()
{
    queue<node> q;
    q.push(node(s1,0));
    
    while(!q.empty())
    {
    	node t = q.front();
    	q.pop();
    	if(t.s == s2)
    	{
    		ans = t.step;
    		return ;
		}
    	
    	int k = t.s.size();
    	for(int i = 0;i< k;i++)//遍历每只青蛙 
	    {
	    	for(int j = -3;j<= 3;j++)//左右各可以走1~3步 
	    	{
	    		string tmp = t.s;
	    		if(i+j< 0||i+j>= k||tmp[i+j]!= '*')
	    			continue;
    			tmp[i+j] = tmp[i];
                tmp[i] = '*';
                if(!mp[tmp])
	            {
	            	mp[tmp] = 1;
	            	q.push(node(tmp,t.step+1));
				}	
			}
	    }
	}
}

int main()
{
    cin>>s1>>s2;
    bfs();
    cout<<ans<<endl;
    return 0;
}


  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值