问题描述
X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。
*WWWBBB
其中,W字母表示白色青蛙,B表示黑色青蛙,*表示空杯子。
X星的青蛙很有些癖好,它们只做3个动作之一:
1. 跳到相邻的空杯子里。
2. 隔着1只其它的青蛙(随便什么颜色)跳到空杯子里。
3. 隔着2只其它的青蛙(随便什么颜色)跳到空杯子里。
对于上图的局面,只要1步,就可跳成下图局面:
WWW*BBB
本题的任务就是已知初始局面,询问至少需要几步,才能跳成另一个目标局面。
输入为2行,2个串,表示初始局面和目标局面。
输出要求为一个整数,表示至少需要多少步的青蛙跳。
样例输入
WWBB
WWBB
样例输出
2
样例输入
WWWBBB
BBBWWW
样例输出
10
网上ac代码:
https://www.cnblogs.com/cff2121/p/9989806.html
#include<iostream>
#include<string>
#include<queue>
#include<set>
#include<algorithm>
using namespace std;
struct state//当前局面
{
string str; //字符串
int step; //从初始到当前状态所需的最小步数
state(string str_,int step_) //构造函数
{
str = str_; step = step_;
}
};
//输入
string begin,end;//初始局面和目标局面
int dir[] = {-3,-2,-1,1,2,3};//可能移动的六个方向
int bfs()
{
queue<state> que; //bfs显示调用队列
set<string> s; //用于标记已经访问的状态
que.push(state(begin,0));//首先加入初始队列
s.insert(begin); //去重
while( que.size() )
{
state current = que.front(); que.pop(); //取出最前端局面
string str = current.str; int step = current.step;
if( str==end ){ //如果到达目标局面
return step;
}
for(int i=0,len=str.length(); i<len; i++)
{
if( str[i]!='*' ){ //只关注空杯子的位置
continue;
}
for(int j=0; j<6; j++) //六个方向
{
int cur = i + dir[j];
if( 0<=cur&&cur<len )
{
swap(str[i],str[cur]);//交换
if( !s.count(str) )
{
s.insert(str);//!!这里就要去重!!
que.push(state(str,step+1));//加入队列
}
swap(str[i],str[cur]);//回溯
}
}
}
}
}
void solve()
{
int ans = bfs();
cout<<ans<<endl;
}
int main()
{
cin>>begin>>end;
solve();
return 0;
}
自己的超时代码:
#include<iostream>
#include<string>
#include<queue>
#include<set>
#include<algorithm>
using namespace std;
struct state//当前局面
{
string str; //字符串
int step; //从初始到当前状态所需的最小步数
state(string str_,int step_) //构造函数
{
str = str_; step = step_;
}
};
//输入
string begin,end;//初始局面和目标局面
int dir[] = {-3,-2,-1,1,2,3};//可能移动的六个方向
int bfs()
{
queue<state> que; //bfs显示调用队列
set<string> s; //用于标记已经访问的状态
que.push(state(begin,0));//首先加入初始队列
s.insert(begin); //去重
while( que.size() )
{
state current = que.front(); que.pop(); //取出最前端局面
string str = current.str; int step = current.step;
if( str==end ){ //如果到达目标局面
return step;
}
for(int i=0,len=str.length(); i<len; i++)
{
if( str[i]!='*' ){ //只关注空杯子的位置
continue;
}
for(int j=0; j<6; j++) //六个方向
{
int cur = i + dir[j];
if( 0<=cur&&cur<len )
{
swap(str[i],str[cur]);//交换
if( !s.count(str) )
{
s.insert(str);//!!这里就要去重!!
que.push(state(str,step+1));//加入队列
}
swap(str[i],str[cur]);//回溯
}
}
}
}
}
void solve()
{
int ans = bfs();
cout<<ans<<endl;
}
int main()
{
cin>>begin>>end;
solve();
return 0;
}