0
点赞
收藏
分享

微信扫一扫

青蛙跳杯子

鱼板番茄 2022-07-12 阅读 59

​经典算法无需注解​

#include<iostream>
#include<algorithm>
#include<map>
#include<algorithm>
#include<queue>
using namespace std;
string s1,s2;
int ans = 0;
map<string,int> mp;

struct Node
{
string s;
int step;
Node(string s,int step):s(s),step(step){}
};
//跳跃后s 和步数
void bfs()
{
//创建队列
queue<Node> q;
q.push(Node(s1,0));//放入第一个

while(!q.empty())
{
Node node = q.front();//取出第一个
q.pop(); //将该对象删除
if(node.s==s2) //找到了 返回
{
ans = node.step;
return;
}
//没找到
int size = node.s.size();
for(int i = 0;i < size;i++)//遍历每一只青蛙
{
for(int j = -3;j<=3;j++) //每一只青蛙可以怎么跳
{
string temp = node.s;
if(i+j<0||i+j>=size||temp[i+j]!='*')
continue;
//青蛙这里开始跳
swap(temp[i+j],temp[i]);
if(!mp[temp])
{
mp[temp] = 1;
q.push(Node(temp,node.step+1));
}
}
}

}

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


举报

相关推荐

0 条评论