问题描述
X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。
*WWWBBB
其中,W字母表示白色青蛙,B表示黑色青蛙,*表示空杯子。
X星的青蛙很有些癖好,它们只做3个动作之一:
1. 跳到相邻的空杯子里。
2. 隔着1只其它的青蛙(随便什么颜色)跳到空杯子里。
3. 隔着2只其它的青蛙(随便什么颜色)跳到空杯子里。
对于上图的局面,只要1步,就可跳成下图局面:WWW*BBB
本题的任务就是已知初始局面,询问至少需要几步,才能跳成另一个目标局面。
输入为2行,2个串,表示初始局面和目标局面。
输出要求为一个整数,表示至少需要多少步的青蛙跳。
样例输入
*WWBB
WWBB*
样例输出
2
样例输入
WWW*BBB
BBB*WWW
样例输出
10
数据规模和约定:
我们约定,输入的串的长度不超过15
资源约定:峰值内存消耗(含虚拟机) < 256M,CPU消耗 < 1000ms
#include<iostream>
#include<bits/stdc++.h>
#include<queue>
#include<math.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int inf=0x3f3f3f3f;
string s1,s2;
map<string,int>m;
struct node{
string s;
int step;
node(string s,int step){
this->s=s;
this->step=step;
}
};
queue<node>q;
int main(){
cin>>s1>>s2;
q.push(node(s1,0));
int len=s1.size();
while(!q.empty()){
node t=q.front();
q.pop();
if(t.s==s2){
cout<<t.step<<endl;
break;
}
for(int i=0;i<s1.size();i++){
if(t.s[i]=='*')
for(int j=max(0,i-3);j<=min(len-1,i+3);j++)//空位范围内可以跳的青蛙
{ string ts=t.s;
if(ts[j]!='*'){
swap(ts[j],ts[i]);
if(m[ts]==0){
m[ts]=1;
q.push(node(ts,t.step+1));
}
}
}
}
}
return 0;
}
https://blog.csdn.net/kiasszz/article/details/84841758借鉴的这位大神的博客