[蓝桥杯][2017年第八届真题]青蛙跳杯子

题目链接:青蛙跳杯子



解题思路: 从第一个空杯子开始宽搜,每次前进1、2、3步判断每次的状态是否合法,如果合法就放入队列。

#include<bits/stdc++.h>
#define x first
#define y second
#define mem(h) memset(h,-1,sizeof h)
#define mcp(a,b) memcpy(a,b,sizeof b)
using namespace std;
typedef long long LL;
typedef unsigned long long ull; 
typedef pair<int,int>PII;
typedef pair<double,double>PDD;
namespace IO{
    
    
	inline LL read(){
    
    
		LL o=0,f=1;char c=getchar();
		while(c<'0'||c>'9'){
    
    if(c=='-')f=-1;c=getchar();}
		while(c>='0'&&c<='9'){
    
    o=o*10+c-'0';c=getchar();}
		return o*f;
	}
}using namespace IO;
//#############以上是自定义技巧(可忽略)########## 
const int N=1e2+7,M=2e5+7,INF=0x3f3f3f3f,mod=1e8+7,P=131;
int dx[6]={
    
    1,2,3,-1,-2,-3};
struct node{
    
    
	int x,step;
	string state;
}now,t;
map<string,bool>st;
string s1,s2;
int sx;
int bfs(){
    
    
	queue<node>q;
	now.x=sx,now.step=0,now.state=s1;
	q.push(now);
	int n=s1.size();
	while(!q.empty()){
    
    
		now=q.front();q.pop();
		if(now.state==s2)return now.step;//如果达到最终状态则返回需要的步数
		for(int i=0;i<6;i++){
    
    //向前后移动1、2、3步
			int tx=now.x+dx[i];
			string s=now.state;
			if(tx<0||tx>=n)continue;
			swap(s[now.x],s[tx]);
			if(st[s])continue;
			st[s]=1;
			t.x=tx,t.step=now.step+1,t.state=s;
			q.push(t);
		}
	}
	return -1;
} 
int main(){
    
    
	cin>>s1>>s2;
	for(int i=0;i<s1.size();i++){
    
    
		if(s1[i]=='*'){
    
    //从第一个空杯子开始宽搜
			sx=i;
			break;
		}
	}
	cout<<bfs()<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43738764/article/details/109013338