[蓝桥杯2017初赛]跳蚱蜢 (bfs)

在这里插入图片描述
答案是:20

#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<set>
#include<queue>
#define ll long long
using namespace std;
///几秒可以出答案,但是有时间限制就不行了,但幸好这是一道填空题
set<string>vis;///已经搜索过的局面   剪枝,降低复杂度
struct node
{
	int pos; ///o的位置,也就是空盘子的位置 
	int step;///到达这个局面的步数
	string str;///局面字符串
};
queue<node>q; ///用来广搜的队列
void bfs(node nex,int i)   ///nex为新的局面,i为移动方式
{
	string s=nex.str;
	swap(s[nex.pos],s[(nex.pos+i+9)%9]);
	///取模是为了模拟循环的数组 
	if(vis.count(s)==0)///如果没有搜索过这个局面 
	{
		vis.insert(s);
		node nexx;
		nexx.str=s;
		nexx.pos=(nex.pos+i+9)%9;
		nexx.step=nex.step+1;
		q.push(nexx);
	}
}
int main()
{
	vis.clear();
	node first;
	first.pos=0;
	first.step=0;
	first.str="012345678";
	q.push(first);
	while(!q.empty())
	{
		node nex;
		nex=q.front();
		if(nex.str=="087654321")
		{
			printf("%d\n",nex.step);
			break;
		}
		else 
		{
			///四种跳法
			bfs(nex,1);
			bfs(nex,-1);
			bfs(nex,2);
			bfs(nex,-2);
			q.pop();
		}
		
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值