[蓝桥杯2017初赛]青蛙跳杯子 (bfs)

在这里插入图片描述

#include<stdio.h>
#include<queue>
#include<math.h>
#include<map>
#include<iostream>
#include<string>
#include<algorithm>
#include<sstream>
using namespace std;
#define ll long long 
string s1,s2;
struct node 
{
	string s;
	int step;
};
queue<node>q;
int dir[6]={1,-1,2,-2,3,-3};
map<string,int>mp;
void bfs()
{
	while(!q.empty())
	{
		q.pop();
	}
	mp.clear();
	node first;
	first.s=s1;
	first.step=0;
	q.push(first);
	while(!q.empty())
	{
		node nex=q.front();
		q.pop();
		if(nex.s==s2)
		{
			cout<<nex.step<<endl;
			return ;
		}
		int len=nex.s.size();
		for(int i=0;i<len;i++)
		{
			for(int j=0;j<6;j++)
			{
				int nex_step=i+dir[j];
				string tmp=nex.s;
				
				if(nex_step>=0&&nex_step<len&&tmp[nex_step]=='*')  ///判断下一步是否符合要求
				///tmp其实已经被mp标记过了,所以只需要判断一下他要走的那一格所组成的字符串是否出现过 
				{
				    swap(tmp[i],tmp[nex_step]);      
				    if(mp[tmp]==0)   ///没出现过,则将其作为下一步走 
				    {
				    mp[tmp]=1;
					node nexx;
					nexx.s=tmp;
                    nexx.step=nex.step+1;
                    q.push(nexx);
					}
					///出现过,则换一个走法形成一个新的字符串 
				}
			}
		}
	}
}
int main()
{
	while(cin>>s1>>s2)
	{
		bfs();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值