#include<iostream>
#include<cmath>
#include<map>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
map<string,int> ans;//存该串是第几步
int n;
int dx[6]={-3,-2,-1,1,2,3};//常用方法用偏移量思维
string str1,str2;
int bfs()
{
queue<string> q;
q.push(str1);
while(q.size())//当队列不空
{
string ss=q.front();//取出队头
q.pop();
int cnt=ans[ss];//记录一下当前队头走了几步
int se=ss.find('*');/*找出第一个空的位置,因为青蛙的三种动作都是往空的地方跳,所以找到一个空的位置,以这个空点为基准*/
for(int i=0;i<6;i++)//遍历所有偏移量
{
int z=dx[i]+se;//保存当前偏移的位置
if(z>=0&&z<n)//判断偏移到的位置是否出界
{
swap(ss[z],ss[se]);/*如果偏移到的位置合法,那就交换,青蛙就由空的位置跳到了该位置
此时ss变成了新串,状态更新了*/
if(!ans.count(ss))//判断当前状态是否走过
{
ans[ss]=cnt+1;//当前这个新状态就成了下一步
if(ss==str2) return ans[ss];//如果当前串符合结果直接返回
q.push(ss);//把当前新状态入队
}
swap(ss[se],ss[z]);/*恢复现场,配合偏移量循环使用,循环会有多种情况,每一种情况走完需要再换回来*/
}
}
}
return -1;
}
int main()
{
cin>>str1>>str2;
n=str1.size();
cout<<bfs()<<endl;
return 0;
}
9. 青蛙跳杯子(蓝桥杯真题)
最新推荐文章于 2024-07-18 19:36:20 发布